I am currently in investigation why JSON.stringify() does not properly parse my object. This is my object I am trying to parse into a JSON string:
var data = [{
name: string,
active: bool,
data: [
value: number,
date: string
]
}]
However when calling JSON.stringify() on my object, I get a result similar to this:
/* JSON.stringify(data) */
[{
name: string,
active: bool,
data: [
[Object],
[Object],
...
]
}]
Is there a nuance to JSON.stringify that causes this to happen? I'd be happy to add more details to my question if it helps clarify any more details.
I think your data array should be like this:
var data = [{
name: string,
active: bool,
data: { //Use {} instead of []
value: number,
date: string
}
}]
You can actually use the second argument to JSON.stringify. Two options for this, you can either specify all the prop names you want stringified:
var data = [{
name: string,
active: bool,
data: [
{value: number},
{date: string}
]
}]
JSON.stringify(data, ['name', 'active', 'data', 'value', 'date'])
=> '[{
"name":"string",
"active":"bool",
"data":[
{"value":"number"},
{"date":"string"}
]}
]'
Or use a replacer function with the same result:
JSON.stringify(data, function replacer(key, value) { return value})
=> '[{
"name":"string",
"active":"bool",
"data":[
{"value":"number"},
{"date":"string"}
]}
]'
Original source: https://javascript.info/json
You need to change the value of data
into a JSON object
instead of a JSON array
to make it work.
JSON.stringify()
seems to parse it without any issues:
working example:
var o1 = [{
"name":"string",
"active":"bool",
"data":{
"value":"number",
"date":"string"
}
}];
var o2 = [{
"name":"string",
"active":"bool",
"data":[
"value",
"number",
"date",
"string"
]
}];
console.log(JSON.stringify(o1)); // outputs: [{"name":"string","active":"bool","data":{"value":"number","date":"string"}}]
console.log(JSON.stringify(o2)); // outputs: [{"name":"string","active":"bool","data":["value","number","date","string"]}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With