2015-10-07 101 views
1

有人可以解释为什么会发生这种情况吗?JSON stringify不完整

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 

在stringily会发生什么事是,当我救了我的JSON到一个文件中(我用的是jsonfile模块)什么也发生。为什么它不打印出我想要的JSON?

回答

1

替换

test['id'] = [] 

test['id'] = {} 

的解释是,阵列的JSON字符串化只使用他们的索引属性(即使未定义)是零和length-1,不是任何其他属性之间他们可能有,比如名为“10-7”的东西(显然这不是数组索引)。

+1

谢谢,就是这么做的。你能解释我试图在那里做什么吗?那为什么发生呢? – SecondLemon

+0

当然。干得好 :) – Touffy