簡體   English   中英

如何在 Javascript 中解析 Json 結果

[英]How to Parse Json Result in Javascript

我有 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 及其值 elizabeth= 0.77777 subtest1=0.802138030529022

JSON 已經針對 Javascript 進行了“解析”,因為 JSON 意味着 JavaScript 對象表示法。 如果您的問題是您不知道如何遍歷 JSON 對象的候選對象,請按照以下方法進行操作:

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

你在你的JSON字符串有錯誤,請檢查這行: "gallery_name": "gallerytest1",,是問題所在。

解析代碼示例:

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

更新:

這是一個如何使用動態屬性的示例。

    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]);
                }
            }
        }

只需簡單地將您的jsonObject到變量var jsonData ,然后使用簡單的循環根據您的json結構遍歷復雜的jsonObject

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.
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM