繁体   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