Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify does not stringify nested arrays

Tags:

json

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.

like image 856
reZach Avatar asked Apr 12 '15 04:04

reZach


3 Answers

I think your data array should be like this:

var data = [{
name: string,
active: bool,
data: { //Use {} instead of []
    value: number,
    date: string
  }
}]
like image 140
hamed Avatar answered Nov 21 '22 02:11

hamed


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

like image 28
L J Avatar answered Nov 21 '22 01:11

L J


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"]}]
like image 43
Eric Avatar answered Nov 21 '22 02:11

Eric