How do I add a Array to a JSON object

岁酱吖の 提交于 2019-12-25 06:24:03

问题


I'm trying to record an objects movements with an attached attribute called data-settings so far I have managed to set up some sort of JSON/Array but I want one of the objects to hold multiple arrays of hashes like so.

{ nPosX: newPX, nPosY: newPY, moves: [{ posX: newPX, posY: newPY, time: 0 }], [{ posX: newPX, posY: newPY, time: 5 }] }

However I'm struggling to add another array to the moves so I only have this:

{ nPosX: newPX, nPosY: newPY, moves: [{ posX: newPX, posY: newPY, time: 0 }] }

How do I push an array with hashes to moves?

Thanks


回答1:


el = { nPosX: newPX, nPosY: newPY, moves: [{ posX: newPX, posY: newPY, time: 0 }] }
el.moves.push({ posX: newPX, posY: newPY, time: 5 })

Gives:

{ nPosX: newPX, nPosY: newPY, moves: [{ posX: newPX, posY: newPY, time: 0 },{ posX: newPX, posY: newPY, time: 5 }] }

Your original syntax isn't valid as you have two arrays containing a single object each attached to the "moves" key. It's not valid JSON.

See : http://www.json.org/




回答2:


No extra square brackets required. So:

moves: [
    { posX: newPX, posY: newPY, time: 0 },
    { posX: newPX, posY: newPY, time: 5 }
]


来源:https://stackoverflow.com/questions/7492472/how-do-i-add-a-array-to-a-json-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!