簡體   English   中英

從復雜的JSON獲取數據

[英]Fetch data from a complex JSON

我是javascript和JSON的新手,已經完成了一項任務。 請在以下鏈接中找到JSON,

http://pastebin.com/0BY3eptF

根據我的說法,上面是一個非常復雜的JSON。

我正在嘗試通過Ajax從WSDL中獲取數據

success: function(api) {
    console.log(api.SearchResult); // trying to fetch information on SearchResult object
}

這行不通。 我想學習如何迭代每個JSON字符串循環。 我還看到了一個數組,它是WSResult []。 帶有說明的整潔javascript將對我有很大幫助。 謝謝。

success: function(api) {} ,這里api仍然是一個字符串,您必須首先將其解析為JSON:

success: function(api) {
    var api = JSON.parse(api);
    console.log(api.SearchResult); // trying to fetch information on SearchResult object
}

一些Web服務以純文本而不是json的形式返回內容類型,您必須手動將其轉換為json。 下面的代碼將幫助您做到這一點。

success: function(api) {
    if (api.constructor === String) {
        api = JSON.parse(api);
    }
    console.log(api.SearchResult);
}

要遍歷api.SearchResult.Result.WSResult數組,請找到以下代碼

$(api.SearchResult.Result.WSResult).each(function (index, val) {
    // here val is single object of WSResult array
});

不是一個完整的答案,但有一些有用的指針:

$ajax({
    url: 'http://myURL',
    // specify the datatype; I think it overrides inferring it from the document MIME type
    dataType: 'json', 
    success: function (api) {
        // provided your data does come back as a JSON document
        // you should be able to access api.SearchResult
    },
    error: function( jsXHR, textStatus, errorThrown) {
        // always have an error handler, so you can see how it went wrong.
    }
);

在此處閱讀有關dataType的部分,因為它可能會解決您的問題

暫無
暫無

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

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