问题
I have created an array of objects that needs to be stored and kept for another page.
The array of objects is similar to this:
var cheese_array = [
{
name: "Chedder",
age: "34",
smelly: true
},
{
name: "Brie",
age: "4",
smelly: false
},
{
name: "Blue Stilton",
age: "13",
smelly: true
}
];
But when I JSON.stringify()
it, it doesn't stringify the objects, only the array. So I end up with and array that looks like this:
[object Object], [object Object], [object Object]
So how do you stringify these objects in this array.
EDIT: This array of objects is then passed to an on click function similar to this:
$("#a-button").click(function() {
var cheese_arr_stringify = JSON.stringify(cheese_array);
sessionStorage.cheeseArray = cheese_arr_stringify;
if(sessionStorage.cheeseArray) {
window.location.href = "../";
}
});
So pretty much, its sets cheese_arr_stringify
to a stringified version of the array of objects. Then it sets this stringified code to a session key. Following this, once it has been set cheeseArray it send it up one directory.
EDIT 2: This is an image of the session key after being stringified. In this case, foodItems is the same as cheeseArray
EDIT 3: @Rayon asked for a fiddle so he could have a look, I made it up and it had worked. The problem was - I feel so stupid now - that I was calling the array instead of the stringified var I had made.
回答1:
Your object misses a comma as shown below:
name: "Blue Stilton",
age: "13"//comma is missing here
smelly: true
JSON.stringify works fine as shown below.
var cheese_array = [
{
name: "Chedder",
age: "34",
smelly: true
},
{
name: "Brie",
age: "4",
smelly: false
},
{
name: "Blue Stilton",
age: "13",
smelly: true
}
];
console.log(JSON.stringify(cheese_array))
However I am not sure how you get a log [object Object], [object Object], [object Object] I am presuming you are console logging something else please check that in your code.
回答2:
You're missing a ,
in your 3rd object, after age:
var cheese_array = [
{
name: "Chedder",
age: "34",
smelly: true
},
{
name: "Brie",
age: "4",
smelly: false
},
{
name: "Blue Stilton",
age: "13",
smelly: true
}
];
var jsonObj = JSON.stringify(cheese_array);
This will now work and display correctly.
回答3:
Update JSON with ,(Comma) in
name: "Blue Stilton",
age: "13",
smelly: true
var cheese_array = [
{
name: "Chedder",
age: "34",
smelly: true
},
{
name: "Brie",
age: "4",
smelly: false
},
{
name: "Blue Stilton",
age: "13",
smelly: true
}
];
var details = JSON.stringify(cheese_array);
alert(details);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
来源:https://stackoverflow.com/questions/38259519/how-do-i-stringify-an-array-of-objects