Search code examples
javascriptjsonstringify

JSON stringify not complete


Can someone explain why this is happening?

var test = JSON

var date = '10-7'

test['id'] = []
test['id'][date] = [[1,2,3]]
test['id'][date].push([1,1,1])

console.log(test) // Output: { id: [ '10-7': [ [Object], [Object] ] ] }
console.log(JSON.stringify(test)) // Output: {"id":[]}
console.log(test['id'][date][0][0]) // Output: 1

What happens at stringily is what is also happening when I'm saving my JSON to a file (I use the jsonfile module). Why does it not print out my JSON like I want to?


Solution

  • Replace

    test['id'] = []
    

    with

    test['id'] = {}
    

    The explanation is that the JSON stringification of arrays uses only their indexed properties (even if undefined) that are between zero and length-1, not any other properties they may have, such as something named "10-7" (which isn't an array index, obviously).