39

我很难理解 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 }
                 ] 
} 

我想创建一个包含以下信息的对象和数组的嵌套结构:

{
"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":[{}]
}]}

但我不知道正确的方法应该是什么。我应该只制作 JavaScript 对象吗?JSON 对这个项目有意义吗?

设置这样的东西的正确语法是什么?

到目前为止,这是我的代码:

$(document).ready(function() {
    $.getJSON('js/orders.json', function(json) {
      $.each(json.problems, function(index, order) {
        $('.loadMeds').append('<p>' + order.name + '</p>')
      });
    });
});
4

5 回答 5

25

第一个代码是 Javascript 代码的示例,类似,但不是 JSON。JSON 不会有 1) 评论和 2)var关键字

您的 JSON 中没有任何注释,但您应该删除var并像这样开始:

orders: {

[{}]符号的意思是“数组中的对象”,而不是您在任何地方都需要的。这不是错误,但对于某些目的来说太复杂了。AssociatedDrug 应该作为一个对象很好地工作:

"associatedDrug": {
                "name":"asprin",
                "dose":"",
                "strength":"500 mg"
          }

此外,空的对象实验室应该装满一些东西。

除此之外,您的代码还可以。您可以将其粘贴到 javascript 中,或使用该JSON.parse()方法或任何其他解析方法(请不要使用 eval

更新 2 回答:

obj.problems[0].Diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name

返回“阿司匹林”。然而,它更适合任何地方的 foreaches

于 2012-05-10T18:20:32.167 回答
17

I successfully solved my problem. Here is my code:

The complex JSON object:

   {
    "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:

$(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");

});

});

于 2012-05-11T20:49:13.127 回答
4

确保遵循JSON的语言定义。在您的第二个示例中,该部分:

"labs":[{
    ""
}]

无效,因为对象必须由零个或多个键值对组成"a" : "b",其中"b"可以是任何有效值。一些解析器可能会自动解释{ "" }为 be { "" : null },但这不是一个明确定义的情况。

此外,您还经常使用嵌套的对象数组 [{}]。我只会在以下情况下这样做:

  1. 数组中的每个对象都没有好的“标识符”字符串。
  2. 在该条目的键值上使用数组有一些明确的原因。
于 2012-05-10T18:19:17.820 回答
0

首先,选择数据结构(xml、json、yaml)通常只包括可读性/大小问题。例如

Json 非常紧凑,但没有人能轻易阅读,很难调试,

XML 很大,但每个人都可以轻松读取/调试它,

Yaml 介于 Xml 和 json 之间。

但是如果你想大量使用 Javascript 和/或你的软件在浏览器-服务器之间进行大量数据传输,你应该使用 Json,因为它是纯 javascript 并且非常紧凑。但是不要尝试将它写成字符串,使用库从对象生成您需要的代码。

希望这可以帮助。

于 2012-05-10T18:17:43.807 回答
0

您可以尝试使用此函数在国王数组的嵌套嵌套数组中查找任何对象。

例子

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
于 2016-08-31T04:47:06.343 回答