Javascript 对象和数组的复杂 JSON 嵌套
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10539797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Complex JSON nesting of objects and arrays
提问by Alex
I am having difficultly with syntax and structure of JSON objects/arrays.
我对 JSON 对象/数组的语法和结构有困难。
{
"accounting" : [
{ "firstName" : "John",
"lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Mary",
"lastName" : "Smith",
"age" : 32 }
],
"sales" : [
{ "firstName" : "Sally",
"lastName" : "Green",
"age" : 27 },
{ "firstName" : "Jim",
"lastName" : "Galley",
"age" : 41 }
]
}
I want to make a nested structure of objects and arrays that would house the following info:
我想创建一个包含以下信息的对象和数组的嵌套结构:
{
"problems": [{
"Diabetes":[{
"medications":[{
"medicationsClasses":[{
"className":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}],
"className2":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}]
}]
}],
"labs":[{
"missing_field": "missing_value"
}]
}],
"Asthma":[{}]
}]}
But I have no idea what the right way to do this should be. Should I just be making JavaScript objects? Does JSON make sense for this project?
但我不知道这样做的正确方法应该是什么。我应该只制作 JavaScript 对象吗?JSON 对这个项目有意义吗?
What is the correct syntax to set something like this up?
设置这样的东西的正确语法是什么?
Here is my code so far:
到目前为止,这是我的代码:
$(document).ready(function() {
$.getJSON('js/orders.json', function(json) {
$.each(json.problems, function(index, order) {
$('.loadMeds').append('<p>' + order.name + '</p>')
});
});
});
采纳答案by Corkscreewe
The first code is an example of Javascript code, which is similar, however not JSON. JSON would not have 1) comments and 2) the var
keyword
第一个代码是 Javascript 代码的示例,与 JSON 类似,但不是 JSON。JSON 不会有 1) 注释和 2)var
关键字
You don't have any comments in your JSON, but you should remove the var
and start like this:
您的 JSON 中没有任何注释,但您应该删除var
并像这样开始:
orders: {
The [{}]
notation means "object in an array" and is not what you need everywhere. It is not an error, but it's too complicated for some purposes. AssociatedDrug should work well as an object:
该[{}]
符号的意思是“数组中的对象”,并不是您在任何地方都需要的。这不是错误,但对于某些目的来说太复杂了。AssociatedDrug 作为一个对象应该可以很好地工作:
"associatedDrug": {
"name":"asprin",
"dose":"",
"strength":"500 mg"
}
Also, the empty object labs should be filled with something.
此外,空的对象实验室应该装满一些东西。
Other than that, your code is okay. You can either paste it into javascript, or use the JSON.parse()
method, or any other parsing method (please don't use eval)
除此之外,你的代码没问题。您可以将其粘贴到 javascript 中,也可以使用该JSON.parse()
方法或任何其他解析方法(请不要使用 eval)
Update 2 answered:
更新 2 回答:
obj.problems[0].Diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name
returns 'aspirin'. It is however better suited for foreaches everywhere
返回“阿司匹林”。然而,它更适合于任何地方的 foreaches
回答by Alex
I successfully solved my problem. Here is my code:
我成功解决了我的问题。这是我的代码:
The complex JSON object:
复杂的 JSON 对象:
{
"medications":[{
"aceInhibitors":[{
"name":"lisinopril",
"strength":"10 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"antianginal":[{
"name":"nitroglycerin",
"strength":"0.4 mg Sublingual Tab",
"dose":"1 tab",
"route":"SL",
"sig":"q15min PRN",
"pillCount":"#30",
"refills":"Refill 1"
}],
"anticoagulants":[{
"name":"warfarin sodium",
"strength":"3 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"betaBlocker":[{
"name":"metoprolol tartrate",
"strength":"25 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"diuretic":[{
"name":"furosemide",
"strength":"40 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"mineral":[{
"name":"potassium chloride ER",
"strength":"10 mEq Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}]
}
],
"labs":[{
"name":"Arterial Blood Gas",
"time":"Today",
"location":"Main Hospital Lab"
},
{
"name":"BMP",
"time":"Today",
"location":"Primary Care Clinic"
},
{
"name":"BNP",
"time":"3 Weeks",
"location":"Primary Care Clinic"
},
{
"name":"BUN",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Cardiac Enzymes",
"time":"Today",
"location":"Primary Care Clinic"
},
{
"name":"CBC",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Creatinine",
"time":"1 Year",
"location":"Main Hospital Lab"
},
{
"name":"Electrolyte Panel",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Glucose",
"time":"1 Year",
"location":"Main Hospital Lab"
},
{
"name":"PT/INR",
"time":"3 Weeks",
"location":"Primary Care Clinic"
},
{
"name":"PTT",
"time":"3 Weeks",
"location":"Coumadin Clinic"
},
{
"name":"TSH",
"time":"1 Year",
"location":"Primary Care Clinic"
}
],
"imaging":[{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
},
{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
},
{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
}
]
}
The jQuery code to grab the data and display it on my webpage:
用于获取数据并将其显示在我的网页上的 jQuery 代码:
$(document).ready(function() {
var items = [];
$.getJSON('labOrders.json', function(json) {
$.each(json.medications, function(index, orders) {
$.each(this, function() {
$.each(this, function() {
items.push('<div class="row">'+this.name+"\t"+this.strength+"\t"+this.dose+"\t"+this.route+"\t"+this.sig+"\t"+this.pillCount+"\t"+this.refills+'</div>'+"\n");
});
});
});
$('<div>', {
"class":'loaded',
html:items.join('')
}).appendTo("body");
});
});
});
回答by devoid
Make sure you follow the language definition for JSON. In your second example, the section:
确保遵循JSON的语言定义。在您的第二个示例中,该部分:
"labs":[{
""
}]
Is invalid since an object must be composed of zero or more key-value pairs "a" : "b"
, where "b"
may be any valid value. Some parsers may automatically interpret { "" }
to be { "" : null }
, but this is not a clearly defined case.
是无效的,因为一个对象必须由零个或多个键值对"a" : "b"
,其中"b"
可以是任何有效的价值。一些解析器可能会自动解释{ "" }
为{ "" : null }
,但这不是一个明确定义的情况。
Also, you are using a nested array of objects[{}]
quite a bit. I would only do this if:
此外,您经常使用嵌套的对象数组[{}]
。我只会在以下情况下这样做:
- There is no good "identifier" string for each object in the array.
- There is some clear reason for having an array over a key-value for that entry.
- 数组中的每个对象都没有好的“标识符”字符串。
- 在该条目的键值上使用数组有一些明确的原因。
回答by hmota
You can try use this function to find any object in nested nested array of arrays of kings.
您可以尝试使用此函数在国王数组的嵌套嵌套数组中查找任何对象。
Example
例子
function findTByKeyValue (element, target){
var found = true;
for(var key in target) {
if (!element.hasOwnProperty(key) || element[key] !== target[key]) {
found = false;
break;
}
}
if(found) {
return element;
}
if(typeof(element) !== "object") {
return false;
}
for(var index in element) {
var result = findTByKeyValue(element[index],target);
if(result) {
return result;
}
}
};
findTByKeyValue(problems,{"name":"somethingElse","strength":"500 mg"}) =====> result equal to object associatedDrug#2
回答by gkaykck
First, choosing a data structure(xml,json,yaml) usually includes only a readability/size problem. For example
首先,选择数据结构(xml、json、yaml)通常只包括可读性/大小问题。例如
Json is very compact, but no human being can read it easily, very hard do debug,
Json 非常紧凑,但没有人可以轻松阅读,很难调试,
Xml is very large, but everyone can easily read/debug it,
XML 非常大,但每个人都可以轻松阅读/调试它,
Yaml is in between Xml and json.
Yaml 介于 Xml 和 json 之间。
But if you want to work with Javascript heavily and/or your software makes a lot of data transfer between browser-server, you should use Json, because it is pure javascript and very compact. But don't try to write it in a string, use libraries to generate the code you needed from an object.
但是如果你想大量使用 Javascript 和/或你的软件在浏览器-服务器之间进行大量数据传输,你应该使用 Json,因为它是纯 javascript 并且非常紧凑。但是不要尝试将其写成字符串,而是使用库从对象生成您需要的代码。
Hope this helps.
希望这可以帮助。