javascript 如何解析返回的 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12735030/
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
How to parse returning JSON object
提问by Rouge
Possible Duplicate:
How to parse json string to javascript object
I am trying to get the values of returned JSON object by using javascript.
我正在尝试使用 javascript 获取返回的 JSON 对象的值。
returned data
返回数据
data: "[{"userID":"35047","testID":"5","subject":"1"..and more}]
in javascript, how do I loop through the userID/testID and value...etc.
在 javascript 中,如何遍历 userID/testID 和 value...等。
Thanks for the help
谢谢您的帮助
回答by nalply
First parse with JSON.parse()
then access them like an object. Example:
首先解析,JSON.parse()
然后像对象一样访问它们。例子:
var obj = JSON.parse(your_data);
then
然后
obj[0].userID
Explanation:
解释:
- The outer
[]
create an array and you can access the array elements by subscripts likeobj[0]
. - The inner
{}
create an object, and you can access the fields by their names. Thereforeobj[0].userID
,obj[0].testID
, etc.
- 外部
[]
创建一个数组,您可以通过像obj[0]
. - 内部
{}
创建一个对象,您可以通过名称访问字段。因此obj[0].userID
,obj[0].testID
等。
Note!
笔记!
JSON.parse()
requires a shim (see json.js/json2.js) in IE6/IE7. It may also be missing in other legacy browsers. You can however include it for all browsers because it detects that a native JSON.parse()
exists.
JSON.parse()
在 IE6/IE7 中需要垫片(请参阅json.js/json2.js)。它也可能在其他旧版浏览器中缺失。但是,您可以将它包含在所有浏览器中,因为它会检测到本机JSON.parse()
存在。
回答by Scott S
jQuery can parse the JSON - http://api.jquery.com/jQuery.parseJSON/
jQuery 可以解析 JSON - http://api.jquery.com/jQuery.parseJSON/
And this post will show you how to iterate over key/value pairs in an object.
这篇文章将向您展示如何迭代对象中的键/值对。
回答by Gung Foo
use JSON.parse()
利用 JSON.parse()
var object = JSON.parse(jsonString);