Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

javascript - 嵌套的JSON对象 - 我是否必须使用数组?(Nested JSON objects - do I have to use arrays for everything?)

Is there any way to have nested objects in JSON so I don't have to make arrays out of everything?(有没有办法在JSON中使用嵌套对象,所以我不必从所有内容中创建数组?)

For my object to be parsed without error I seem to need a structure like this:(为了我的对象没有错误地解析我似乎需要这样的结构:) {"data":[{"stuff":[ {"onetype":[ {"id":1,"name":"John Doe"}, {"id":2,"name":"Don Joeh"} ]}, {"othertype":[ {"id":2,"company":"ACME"} ]}] },{"otherstuff":[ {"thing": [[1,42],[2,2]] }] }]} If I fetch this object into a variable called "result" I have to access the nested objects like this:(如果我将此对象提取到名为“result”的变量中,我必须像这样访问嵌套对象:) result.data[0].stuff[0].onetype[0] and(和) result.data[1].otherstuff[0].thing[0] This seems clumsy and redundant to me, if possible I would prefer:(这对我来说似乎很笨拙和多余,如果可能的话我宁愿:) result.stuff.onetype[0] and(和) result.otherstuff.thing But how can I use the object keys directly when everything is an array?(但是当一切都是数组时,如何直接使用对象键?) To my confused and uneducated mind something like this would seem more appropriate:(对于我困惑和未受过教育的人来说,这样的事情似乎更合适:) {"data": {"stuff": {"onetype":[ {"id":1,"name": ""}, {"id":2,"name": ""} ]} {"othertype":[ {"id":2,"xyz": [-2,0,2],"n":"Crab Nebula","t":0,"c":0,"d":5} ]} } {"otherstuff": {"thing": [[1,42],[2,2]] } } } I've probably misunderstood something fundamental here, but I cannot get the jQuery parser (nor the native FF parser used by jQuery 1.4) to accept the second style object.(我可能在这里误解了一些基本的东西,但我无法获得jQuery解析器(也不是jQuery 1.4使用的本机FF解析器)来接受第二个样式对象。) If anyone can enlighten me it would be gratefully appreciated!(如果有人能够启发我将非常感激!)   ask by John Schulze translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need to use arrays.(您不需要使用数组。)

JSON values can be arrays, objects, or primitives (numbers or strings).(JSON值可以是数组,对象或基元(数字或字符串)。) You can write JSON like this:(您可以像这样编写JSON:) { "stuff": { "onetype": [ {"id":1,"name":"John Doe"}, {"id":2,"name":"Don Joeh"} ], "othertype": {"id":2,"company":"ACME"} }, "otherstuff": { "thing": [[1,42],[2,2]] } } You can use it like this:(你可以像这样使用它:) obj.stuff.onetype[0].id obj.stuff.othertype.id obj.otherstuff.thing[0][1] //thing is a nested array or a 2-by-2 matrix. //I'm not sure whether you intended to do that.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...