简体   繁体   English

如何在JavaScript中解析JSON对象

[英]How do I parse a JSON object in JavaScript

I have the following function, which currently just displays the object returned from the GET request to the console. 我有以下函数,当前仅显示从GET请求返回的对象到控制台。 What I need to do is parse the "data" object so that I can return the "output" string from data to my web page. 我需要做的是解析“数据”对象,以便可以将数据中的“输出”字符串返回到我的网页。 Any help would be greatly appreciated. 任何帮助将不胜感激。

window.onload = function() {
    var output = $.ajax({
        url: 'https://ajith-holy-bible.p.mashape.com/GetVerseOfaChapter?Book=John&chapter=3&Verse=16', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
        type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
        data: {}, // Additional parameters here
        dataType: 'json',
        success: function (data) {
            //
            //Change data.source to data.something , where something is whichever part of the object you want returned.
            //To see the whole object you can output it to your browser console using:
            console.log(data);
        },
        error: function (err) {
            alert(err);
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("X-Mashape-Authorization", "my_key_here"); // Enter here your Mashape key
        }
    });
}

I'm not sure how your JSON looks like but let's say is 我不确定您的JSON的样子,但可以说是

{
    "foo": "some value",
    "bar": "some other value"
}

then you could do: 那么您可以执行以下操作:

success: function (data) {

    console.log(data);

    var dataObj = $.parseJSON(data);

    $.each(dataObj, function(key, value) {
        if(key == "foo") {
            // do something with foo's value
            console.log(value);         
        }
        if(key == "bar") {
            // do something with bar's value
            console.log(value); 
        }
    });

}

if 如果

dataType: 'json',

and your response looks like 你的回应看起来像

{
   foo:'bar'
}

you can just access like 您可以像访问

    success: function (data) {

     console.log(data.foo)

which will output 将输出

"bar"

also it is unnessecary to assign the request to the variable "output" 将请求分配给变量“输出”也是不必要的

if this does niot work for you you should json-lint your response, maybe the headers are not correct etc. ... 如果这对您没有帮助,则您应该json-lint您的响应,也许标题不正确,等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM