如何在Javascript中解析Json结果

时间:2016-04-03 09:35:30

标签: javascript json

我有json结果我有代码,但它只适用于唯一键 在我的数据中,每个值都有不同的键 请帮帮我

{
    "images": [
    {
        "time": 2.86091,
        "transaction":
        {
            "status": "Complete",
            "subject": "test2",
            "confidence": 0.77,
            "gallery_name": "gallerytest1",
        },
        "candidates": [
        {
          "subtest1": "0.802138030529022",
          "enrollment_timestamp": "1416850761"
        },
        {
          "elizabeth": "0.802138030529022",
          "enrollment_timestamp": "1417207485"
        },
        {
          "elizabeth": "0.777253568172455",
          "enrollment_timestamp": "1416518415"
        },
        {
          "elizabeth": "0.777253568172455",
          "enrollment_timestamp": "1416431816"
        }
        ]
    } ]
}

我想从中解析所有catidates及其值 伊丽莎白= 0.77777 subtest1 = 0.802138030529022

3 个答案:

答案 0 :(得分:0)

JSON已被解析'对于Javascript,JSON表示JavaScript Object Notation。 如果您的问题是您不知道如何遍历JSON对象的候选者,请按以下步骤操作:

var candidates = jsonObject.images[0].candidates
for (var key in candidates) {
        alert(jsonObject[key]);
}

答案 1 :(得分:0)

您的json字符串中有错误,请检查以下行:"gallery_name": "gallerytest1", char ,就是问题所在。

解析的代码示例:

var data = JSON.parse(jsonString);
alert(data["images"][0]["candidates"][0]["subtest1"]);

<强>更新

以下是如何使用dinamic属性的示例。

    var jsonData = JSON.parse(jsonString);

        for(i=0; i < jsonData["images"].length; i++) { // foreach image
            var candidates = jsonData["images"][i]["candidates"]; // array of candidates

            for (j = 0; j < candidates.length; j++) { // foreach candidate
                var candidate = candidates[j]; // single candidate

                for (var key in candidate){ // foreach candidate property

                    // this if condition is required when working with for loop on this way.
                    // for more visit http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
                    if (typeof candidate[key] === 'function') {
                       continue;
                    }
                    alert("Key: " + key + "\nValue: " + candidate[key]);
                }
            }
        }

答案 2 :(得分:0)

只需将您的jsonObject引用到变量var jsonData,然后根据您的jsonObject结构使用简单循环迭代复杂json

var jsonData = {.....}  // Your JSON Object that you added in your Question.

此处jsonData包含您的复杂jsonObject现在通过json元素进行迭代。

for(i=0; i < jsonData.images.length; i++){ //iterate throughout the Images Node Array.

    var candidates = obj.images[i].candidates; //Get the Candidate Node of each Image.

    for(j=0; j < candidates.length; j++){ //iterate throughout the Candidates Node Array.

       console.log(candidates[j]); // get the each Candidate to print on Console log of Web Browser.
  }