Javascript 提取json数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7988726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
extracting json data
提问by Paul
I have some json from a remote server and the results are returned like this:
我有一些来自远程服务器的 json,结果是这样返回的:
[{"item1":"tag1","a1":"b1"},{"item2":"tag2","a2":"b2"}]
How would I get the value of a1 and a2?
我如何获得 a1 和 a2 的值?
Thanks
谢谢
回答by Matt Ball
Use JSON.parse()
if the data is still in string form:
使用JSON.parse()
如果数据仍然是字符串形式:
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"
Demo: http://jsfiddle.net/mattball/WK9gz/
演示:http: //jsfiddle.net/mattball/WK9gz/
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.
由于您使用的是 jQuery,换掉$.get()
for $.getJSON()
,jQuery 会自动为您解析 JSON。在success
回调内部,您将有一个普通的 JavaScript 对象可以使用——不需要解析。
$.getJSON('http://example.com/foo/bar/baz', function (data)
{
console.log(data[0].a1); // logs "b1"
console.log(data[1].a2); // logs "b2"
});