且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在javascript中将字符串转换为对象数组的***方法?

更新时间:2021-12-09 21:28:32

我认为***的方法是这样做,如 Douglas Crockford(最大的 JavaScript 大师之一)建议正在使用JSON 原生解析器,因为它不仅比 eval() 快,而且还更多安全.

I think that the best way of doing this, as Douglas Crockford (one of the biggests gurus of JavaScript) suggests in here is using the JSON native parser, as it is not only faster than the eval(), it's also more secure.

原生 JSON 解析器已经在:

Native JSON parser is already available in:

  • Firefox 3.5+
  • IE 8+
  • Opera 10.5+
  • Safari Safari 4.0.3+
  • Chrome(不知道是哪个版本)

Crockford 在 javascript 中做了一个安全的后备,称为 json2.js,这是对 eval() 方法的改编,添加了一些安全位和原生 JSON 解析器 API.您只需要包含该文件,删除它的第一行,然后使用本机 JSON 解析器,如果它不存在,json2 将完成这项工作.

And Crockford has made a safe fallback in javascript, called json2.js, which is an adaption of the eval() approach, with some security bits added and with the native JSON parsers API. You just need to include that file, remove its first line, and use the native JSON parser, and if it's not present json2 would do the work.

这是一个例子:

var myJSONString = '{ "a": 1, "b": 2 }',
    myObject = JSON.parse(myJSONString);

解析后,您将获得一个具有 ab 属性的对象,并且您可能知道,您可以将对象视为哈希表或 关联数组 在 JavaScript 中,因此您可以像这样访问值:

Once parsed you'll get an object with attributes a and b, and as you may know, you can treat an object as a hash table or associative array in JavaScript, so you would be able to access the values like this:

myObject['a'];

如果你只想要一个简单的数组而不是一个关联的数组,你可以这样做:

If you just want a simple array and not an associative one you could do something like:

var myArray = [];
for(var i in myObject) {
    myArray.push(myObject[i]);
}

最后,虽然在纯 JavaScript 中不是必需的,JSON 规范需要双引号成员的键.因此,没有它,navite 解析器将无法工作.如果我是你,我会添加它,但如果不可能使用 var myObject = eval( "(" + myString + ")" ); 方法.

Lastly, although not necessary in plain JavaScript, the JSON spec requires double quoting the key of the members. So the navite parser won't work without it. If I were you I would add it, but if it is not possible use the var myObject = eval( "(" + myString + ")" ); approach.