提取json数据 [英] extracting json data
本文介绍了提取json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从远程服务器上获取了一些json,结果返回如下:
I have some json from a remote server and the results are returned like this:
[{"item1":"tag1","a1":"b1"},{"item2":"tag2","a2":"b2"}]
我如何获得a1和a2的值?
How would I get the value of a1 and a2?
谢谢
推荐答案
使用 JSON.parse()
如果数据仍为字符串形式:
Use JSON.parse()
if the data is still in string form:
var rawData = '[{"item1":"tag1","a1":"b1"},{"item2":"tag2","a2":"b2"}]';
var parsed = JSON.parse(rawData);
console.log(parsed[0].a1); // logs "b1"
console.log(parsed[1].a2); // logs "b2"
演示: http://jsfiddle.net/mattball/WK9gz/
因为您使用的是jQuery,所以将$.get()
替换为$.getJSON()
,jQuery会自动为您解析JSON.在success
回调内部,您将具有一个与—一起使用的普通JavaScript对象.无需解析.
Since you're using jQuery, swap out $.get()
for $.getJSON()
and jQuery will automagically parse the JSON for you. Inside of the success
callback, you'll have a normal JavaScript object to work with — no parsing required.
$.getJSON('http://example.com/foo/bar/baz', function (data)
{
console.log(data[0].a1); // logs "b1"
console.log(data[1].a2); // logs "b2"
});
这篇关于提取json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文