在javascript中将字符串转换为对象数组的最佳方法? [英] Best way to convert string to array of object in javascript?

查看:40
本文介绍了在javascript中将字符串转换为对象数组的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 javascript 中将下面的字符串转换为数组.

I want to convert below string to an array in javascript.

{a:12, b:c, foo:bar}

如何将此字符串转换为对象数组?有什么好主意吗?

How do I convert this string into array of objects? Any cool idea?

推荐答案

我认为最好的方法是这样做,如 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.

这篇关于在javascript中将字符串转换为对象数组的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆