本文介绍了在JavaScript中解析JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaScript中解析JSON字符串。响应类似于

I want to parse a JSON string in JavaScript. The response is something like

var response = '{"result":true,"count":1}';

如何获取值结果和从这个计算

推荐答案

大多数浏览器都支持,在ECMA-262第5版(JavaScript所基于的规范)中定义。它的用法很简单:

Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JavaScript is based on). Its usage is simple:

var json = '{"result":true,"count":1}',
    obj = JSON.parse(json);

alert(obj.count);

/* or ES6 */

const json = '{"result":true,"count":1}' || {};
const { result, count } = JSON.parse(json);
alert(result);
alert(count);

对于没有的浏览器,您可以使用。

For the browsers that don't you can implement it using json2.js.

如上所述注释,如果你已经在使用jQuery,那么有一个 $。parseJSON 函数映射到 JSON.parse 如果可用,或者在旧浏览器中使用 eval 的形式。但是,这会执行额外的,不必要的检查,这些检查也由 JSON.parse 执行,因此为了获得最好的全面性能,我建议使用它,如下所示:

As noted in the comments, if you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:

var json = '{"result":true,"count":1}',
    obj = JSON && JSON.parse(json) || $.parseJSON(json);

这将确保您使用原生 JSON.parse 立即,而不是让jQuery在将字符串传递给本机解析函数之前对字符串执行完整性检查。

This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.

这篇关于在JavaScript中解析JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:45