在 JavaScript 中解析 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4935632/
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
Parse JSON in JavaScript?
提问by Andy E
I want to parse a JSON string in JavaScript. The response is something like
我想用 JavaScript 解析一个 JSON 字符串。响应类似于
var response = '{"result":true,"count":1}';
How can I get the values result
and count
from this?
我怎样才能获得的值result
,并count
从这个?
回答by Andy E
The standard way to parse JSON in JavaScript is JSON.parse()
在 JavaScript 中解析 JSON 的标准方法是 JSON.parse()
The JSON
API was introduced with ES5(2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:
该JSON
API 是随ES5(2011)引入的,此后已在超过 99% 的市场份额浏览器和 Node.js 中实现。它的用法很简单:
const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);
The only time you won't be able to use JSON.parse()
is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. Alternatively, you may be in an esoteric JavaScript environment that doesn't include the standard APIs. In these cases, use json2.js, the reference implementation of JSON written by Douglas Crockford, the inventor of JSON. That library will provide an implementation of JSON.parse()
.
唯一无法使用的情况JSON.parse()
是您正在为旧浏览器编程,例如 IE 7 (2006)、IE 6 (2001)、Firefox 3 (2008)、Safari 3.x (2009) 等. 或者,您可能处于不包含标准 API 的深奥 JavaScript 环境中。在这些情况下,请使用json2.js,这是 JSON的发明者Douglas Crockford编写的 JSON 参考实现。该库将提供JSON.parse()
.
When processing extremely large JSON files, JSON.parse()
may choke because of its synchronous nature and design. To resolve this, the JSON website recommends third-party libraries such as Oboe.jsand clarinet, which provide streaming JSON parsing.
在处理非常大的 JSON 文件时,JSON.parse()
可能会因为它的同步性质和设计而窒息。为解决此问题,JSON 网站推荐使用Oboe.js和clarinet等第三方库,它们提供流式 JSON 解析。
jQuery once had a $.parseJSON()
function, but it was deprecated with jQuery 3.0. In any case, for a long time it was nothing more than a wrapper around JSON.parse()
.
jQuery 曾经有一个$.parseJSON()
函数,但它在 jQuery 3.0 中被弃用了。无论如何,在很长一段时间内,它只不过是JSON.parse()
.
回答by Clarence Fredericks
WARNING!
This answer stems from an ancient era of JavaScript programming during which there was no builtin way to parse JSON. The advice given here is no longer applicable and probably dangerous. From a modern perspective, parsing JSON by involving jQuery or calling eval() is nonsense. Unless you need to support IE 7 or Firefox 3.0, the correct way to parse JSON is JSON.parse().
警告!
这个答案源于 JavaScript 编程的古老时代,在此期间没有内置的方法来解析 JSON。这里给出的建议不再适用,而且可能很危险。从现代的角度来看,通过涉及 jQuery 或调用 eval() 来解析 JSON 是无稽之谈。除非您需要支持 IE 7 或 Firefox 3.0,否则解析 JSON 的正确方法是JSON.parse()。
First of all, you have to make sure that the JSON code is valid.
首先,您必须确保 JSON 代码有效。
After that, I would recommend using a JavaScript library such as jQuery or Prototype if you can because these things are handled well in those libraries.
在那之后,如果可以的话,我会推荐使用 JavaScript 库,例如 jQuery 或 Prototype,因为这些东西在这些库中处理得很好。
On the other hand, if you don't want to use a library and you can vouch for the validity of the JSON object, I would simply wrap the string in an anonymous function and use the eval function.
另一方面,如果您不想使用库并且可以保证 JSON 对象的有效性,我只需将字符串包装在匿名函数中并使用 eval 函数。
This is not recommended if you are getting the JSON object from another source that isn't absolutely trusted because the eval function allows for renegade code if you will.
如果您从另一个并非绝对可信的来源获取 JSON 对象,则不建议这样做,因为如果您愿意, eval 函数允许使用叛徒代码。
Here is an example of using the eval function:
以下是使用 eval 函数的示例:
var strJSON = '{"result":true,"count":1}';
var objJSON = eval("(function(){return " + strJSON + ";})()");
alert(objJSON.result);
alert(objJSON.count);
If you control what browser is being used or you are not worried people with an older browser, you can always use the JSON.parse method.
如果您控制正在使用的浏览器,或者您不担心使用旧浏览器的人,您始终可以使用 JSON.parse 方法。
This is really the ideal solution for the future.
这确实是未来的理想解决方案。
回答by milestyle
If you are getting this from an outside site it might be helpful to use jQuery's getJSON. If it's a list you can iterate through it with $.each
如果您是从外部站点获取此信息,则使用 jQuery 的 getJSON 可能会有所帮助。如果它是一个列表,你可以用 $.each 遍历它
$.getJSON(url, function (json) {
alert(json.result);
$.each(json.list, function (i, fb) {
alert(fb.result);
});
});
回答by huwiler
If you want to use JSON 3for older browsers, you can load it conditionally with:
如果你想对旧浏览器使用JSON 3,你可以有条件地加载它:
<script>
window.JSON ||
document.write('<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.min.js"><\/scr'+'ipt>');
</script>
Now the standard window.JSON
object is available to you no matter what browser a client is running.
现在,window.JSON
无论客户端运行什么浏览器,您都可以使用标准对象。
回答by Joke_Sense10
The following example will make it clear:
下面的例子将说明:
let contactJSON = '{"name":"John Doe","age":"11"}';
let contact = JSON.parse(contactJSON);
console.log(contact.name + ", " + contact.age);
// Output: John Doe, 11
回答by Jenna Leaf
If you pass a string variable (a well-formed JSON string) to JSON.parse from MVC @Viewbag that has doublequote, '"', as quotes, you need to process it before JSON.parse (jsonstring
)
如果你将一个字符串变量(一个格式良好的 JSON 字符串)从 MVC @Viewbag 传递给 JSON.parse,它有双引号,'"',作为引号,你需要在 JSON.parse ( jsonstring
)之前处理它
var jsonstring = '@ViewBag.jsonstring';
jsonstring = jsonstring.replace(/"/g, '"');
回答by Teja
You can either use the eval function as in some other answers. (Don't forget the extra braces.) You will know why when you dig deeper), or simply use the jQuery function parseJSON
:
您可以像在其他一些答案中一样使用 eval 函数。(不要忘记额外的大括号。)当你深入挖掘时你就会知道为什么),或者简单地使用 jQuery 函数parseJSON
:
var response = '{"result":true , "count":1}';
var parsedJSON = $.parseJSON(response);
OR
或者
You can use this below code.
您可以使用下面的代码。
var response = '{"result":true , "count":1}';
var jsonObject = JSON.parse(response);
And you can access the fields using jsonObject.result
and jsonObject.count
.
您可以使用jsonObject.result
和访问字段jsonObject.count
。
Update:
更新:
If your output is undefined
then you need to follow THIS answer. Maybe your json string has an array format. You need to access the json object properties like this
如果您的输出是,undefined
那么您需要遵循这个答案。也许您的 json 字符串具有数组格式。您需要像这样访问 json 对象属性
var response = '[{"result":true , "count":1}]'; // <~ Array with [] tag
var jsonObject = JSON.parse(response);
console.log(jsonObject[0].result); //Output true
console.log(jsonObject[0].count); //Output 1
回答by Jorgesys
The easiest way using parse()
method:
最简单的使用parse()
方法:
var response = '{"a":true,"b":1}';
var JsonObject= JSON.parse(response);
this is an example of how to get values:
这是如何获取值的示例:
var myResponseResult = JsonObject.a;
var myResponseCount = JsonObject.b;
回答by Pushkar Kathuria
JSON.parse() converts any JSON String passed into the function, to a JSON object.
JSON.parse() 将任何传入函数的 JSON 字符串转换为 JSON 对象。
For better understanding, press F12to open the Inspect Element of your browser, and go to the console to write the following commands:
为便于理解,按F12打开浏览器的Inspect Element,在控制台中编写以下命令:
var response = '{"result":true,"count":1}'; // Sample JSON object (string form)
JSON.parse(response); // Converts passed string to a JSON object.
Now run the command:
现在运行命令:
console.log(JSON.parse(response));
You'll get output as Object {result: true, count: 1}.
您将获得输出为 Object {result: true, count: 1}。
In order to use that object, you can assign it to the variable, let's say obj
:
为了使用该对象,您可以将其分配给变量,例如obj
:
var obj = JSON.parse(response);
Now by using obj
and the dot(.) operator you can access properties of the JSON Object.
现在通过使用obj
和 dot(.) 运算符,您可以访问 JSON 对象的属性。
Try to run the command
尝试运行命令
console.log(obj.result);
回答by El Ronnoco
Without using a library you can use eval
- the only time you should use. It's safer to use a library though.
不使用您可以使用的库eval
- 您应该使用的唯一时间。不过使用库更安全。
eg...
例如...
var response = '{"result":true , "count":1}';
var parsedJSON = eval('('+response+')');
var result=parsedJSON.result;
var count=parsedJSON.count;
alert('result:'+result+' count:'+count);