对象和数组的复杂JSON嵌套

时间:2012-05-10 18:07:29

标签: javascript jquery arrays json object

我对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>')
      });
    });
});

5 个答案:

答案 0 :(得分:22)

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

您的JSON中没有任何评论,但您应该删除var并从这样开始:

orders: {

[{}]符号表示“数组中的对象”并不是您需要的所有内容。这不是错误,但对于某些目的而言太复杂了。 AssociatedDrug应该很好地作为一个对象:

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

此外,空物体实验室应该装满东西。

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

更新2回答:

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

返回'阿司匹林'。然而,它更适合各地的森林

答案 1 :(得分:14)

我成功地解决了我的问题。这是我的代码:

复杂的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"    
        }
    ]
}

用于获取数据并将其显示在我的网页上的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");

});

});

答案 2 :(得分:4)

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

"labs":[{
    ""
}]

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

此外,您正在使用嵌套的对象数组 [{}]。我只会这样做:

  1. 数组中的每个对象都没有好的“标识符”字符串。
  2. 有一个明确的理由让数组超过该条目的键值。

答案 3 :(得分:1)

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

Json非常紧凑,但没有人能够轻松阅读,非常难以进行调试,

Xml非常大,但每个人都可以轻松地读取/调试它,

Yaml介于Xml和json之间。

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

希望这有帮助。

答案 4 :(得分: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