如何使用javascript从JSON返回的对象中提取特定值?

时间:2015-01-13 23:19:43

标签: javascript jquery json

我正在使用对Sunlight Foundations API的调用来执行codecademy javascript API教程。我已经完成了完整的codecacemy javascript课程,可能会遗漏soemthign simple。

我想从返回的JSON对象中提取结果的数量,由于jquery,该对象当前以HTML格式显示。

这是返回对象的示例:

{
"num_found": 347,
"results": [
    {
        "speaker_state": "NC",
        "speaker_first": "Virginia",
        "congress": 111,
        "title": "CULTIVATING AMERICAN ENERGY RESOURCES",
        "origin_url": "http://origin.www.gpo.gov/fdsys/pkg/CREC-2009-07-30/html/CREC-2009-07-30-pt1-PgH9197.htm",
        "number": 117,
        "pages": "H9197-H9203",
        "volume": 155,
        "chamber": "House",
        "session": 1,
        "speaking": [
            "Well, I think that this is a great segue to talk about the other subject that we wanted to talk about tonight, which is health care, and what is happening with the health care debate."
        ],
        "capitolwords_url": "http://capitolwords.org/date/2009/07/30/H9197_cultivating-american-energy-resources/",
        "speaker_party": "R",
        "date": "2009-07-30",
        "bills": null,
        "bioguide_id": "F000450",
        "order": 14,
        "speaker_last": "Foxx",
        "speaker_raw": "ms. foxx"
    },
    ...
]

}

以下是显示结果的最后一条陈述:

  var query_params = { apikey: 'f6ab5f2e4f69444b9f2c0a44d9a5223d',
                   phrase: word
                 };

  var endpoint = 'http://capitolwords.org/api/text.json'

  var options = {
    data: query_params,
    type: 'GET',
    dataType: 'jsonp'      
  };

    var request = jQuery.ajax(endpoint, options)
                        .done(showResponse);

如果上面的最后一行返回对象,我如何将方法链接到.done(),它将提取例如“num_found”?

提供的提示是链接方法,但我不太明白。谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

您可以在AJAX请求(成功)完成后通过添加“success”选项来执行函数:

var query_params = { 

   apikey:    'f6ab5f2e4f69444b9f2c0a44d9a5223d',
   phrase:    word
};

$.ajax({

   url:       'http://capitolwords.org/api/text.json',
   data:      query_params,
   type:      'GET',
   dataType:  'jsonp',
   success:   showResponse
});

function showResponse(response) {

   alert(response.num_found);
}

它将作为对象从服务器传递响应,因为jQuery为您完成所有复杂的JSONP工作。此示例将执行函数showResponse并警告num_found的值。

这也可以帮助您:http://learn.jquery.com/ajax/working-with-jsonp/

答案 1 :(得分:1)

不确定,但我认为这就是你想要的:

.done(function(data){
     var myVar = .....
     showResponse(myVar);
});