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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:59:56  来源:igfitidea点击:

How to parse returning JSON object

javascriptjqueryajax

提问by Rouge

Possible Duplicate:
How to parse json string to javascript object

可能的重复:
如何将 json 字符串解析为 javascript 对象

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 like obj[0].
  • The inner {}create an object, and you can access the fields by their names. Therefore obj[0].userID, obj[0].testID, etc.
  • 外部[]创建一个数组,您可以通过像obj[0].
  • 内部{}创建一个对象,您可以通过名称访问字段。因此obj[0].userIDobj[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.

这篇文章将向您展示如何迭代对象中的键/值对。

How do I loop through or enumerate a JavaScript object?

如何循环或枚举 JavaScript 对象?

回答by Gung Foo

use JSON.parse()

利用 JSON.parse()

var object = JSON.parse(jsonString);

回答by A. Matías Quezada

First of all you need to parse the JSON, if you are targeting only thisgreen browsers, then you can simply do:

首先你需要解析 JSON,如果你只针对这个绿色浏览器,那么你可以简单地做:

var myJson = JSON.parse(data);

If not you can load a extern parse library like this oneand then do it the same way.

如果没有,您可以加载像这样的外部解析库,然后以相同的方式执行。