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

时间:2022-07-14 22:26:21

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

我想把下面的字符串转换成javascript中的数组。

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

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

如何将这个字符串转换成对象数组?酷的想法吗?

6 个解决方案

#1


76  

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本机解析器,因为它不仅比eval()快,而且更安全。

Native JSON parser is already available in:

本机JSON解析器已经在:

  • Firefox 3.5+
  • Firefox 3.5 +
  • IE 8+
  • IE 8 +
  • Opera 10.5+
  • Opera 10.5 +
  • Safari Safari 4.0.3+
  • Safari Safari 4.0.3 +
  • Chrome (don't know which version)
  • Chrome(不知道是哪个版本)

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.

Crockford在javascript上做了一个安全的回退,叫做json2。js,它是eval()方法的一种改进,添加了一些安全位,并使用本机JSON解析器API。您只需要包含该文件,删除它的第一行,并使用本地的JSON解析器,如果不存在json2,就可以完成这项工作。

Here is an example:

这是一个例子:

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

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:

一旦解析,就会得到一个带有属性a和b的对象,正如您可能知道的那样,您可以将对象看作是JavaScript中的散列表或关联数组,因此您将能够访问如下的值:

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]);
}

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中没有必要,但JSON规范要求对成员的键进行两次引用。所以navite解析器没有它就不能工作。如果我是你,我会添加它,但是如果不可能使用var myObject = eval("(" + myString + ")");的方法。

#2


7  

The simplest, but unsafe way to do it is:

最简单但不安全的方法是:

eval('(' + myJSONtext + ')')

But since this will interpret any javascript code, it has security holes. To protect against this use a json parser. If you're using a framework (jquery, mootools, etc.) there's a framework-specific call. Most of them are based on Douglas Crawford's parser available at http://www.json.org/js.html.

但是由于这将解释任何javascript代码,所以它有安全漏洞。要避免这种情况,请使用json解析器。如果您正在使用框架(jquery、mootools等),就会有一个特定于框架的调用。大多数解析器都基于Douglas Crawford的解析器,可以在http://www.json.org/js.html中找到。

#3


7  

Since your string is malformed JSON, a JSON parser can't parse it properly and even eval() will throw an error. It's also not an Array but a HashMap or simply an Object literal (malformed). If the Object literal will only contain number and string values (and no child objects/arrays) you can use the following code.

由于您的字符串是畸形的JSON, JSON解析器无法正确解析它,甚至eval()也会抛出一个错误。它也不是数组,而是HashMap,或者只是对象文字(畸形)。如果对象文字只包含数字和字符串值(没有子对象/数组),您可以使用以下代码。

function malformedJSON2Array (tar) {
    var arr = [];
    tar = tar.replace(/^\{|\}$/g,'').split(',');
    for(var i=0,cur,pair;cur=tar[i];i++){
        arr[i] = {};
        pair = cur.split(':');
        arr[i][pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
    }
    return arr;
}

malformedJSON2Array("{a:12, b:c, foo:bar}");
// result -> [{a:12},{b:'c'},{foo:'bar'}]

That code will turn your string into an Array of Objects (plural).

该代码将把字符串转换为对象数组(复数)。

If however you actually wanted a HashMap (Associative Array) and NOT an array, use the following code:

如果你想要一个HashMap(关联数组)而不是数组,请使用以下代码:

function malformedJSON2Object(tar) {
    var obj = {};
    tar = tar.replace(/^\{|\}$/g,'').split(',');
    for(var i=0,cur,pair;cur=tar[i];i++){
        pair = cur.split(':');
        obj[pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
    }
    return obj;
}

malformedJSON2Object("{a:12, b:c, foo:bar}");
// result -> {a:12,b:'c',foo:'bar'}

The above code will become a lot more complex when you start nesting objects and arrays. Basically you'd have to rewrite JSON.js and JSON2.js to support malformed JSON.

当开始嵌套对象和数组时,上面的代码将变得复杂得多。基本上你需要重写JSON。js和JSON2。js支持格式错误的JSON。

Also consider the following option, which is still bad I admit, but marginally better then sticking JSON inside an HTML tag's attribute.

还可以考虑下面的选项,我承认这仍然很糟糕,但比在HTML标记的属性中插入JSON要好一点。

<div id="DATA001">bla</div>
<!-- namespacing your data is even better! -->
<script>var DATA001 = {a:12,b:"c",foo:"bar"};</script>

I am assuming you omit quote marks in the string because you had put it inside an HTML tag's attribute and didn't want to escape quotes.

我假设您省略了字符串中的引号,因为您已经将它放在HTML标记的属性中,并且不希望转义引号。

#4


2  

You can use "for in"

你可以用for in

var myObject = {a:'12', b:'c', foo:'bar'};
var myArray = [];

for(key in myObject) {
    var value = myObject[key];
    myArray[key] = value;
}

myArray['a']; // returns 12

Notes: considering that myObject only have one level of key-value pairs.

注意:考虑到myObject只有一个级别的键-值对。

#5


1  

If you're using jQuery, there's the $.parseJSON() function. It throws an exception if the string is malformed, and "Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from parseJSON. Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string"

如果使用jQuery,可以使用$. parsejson()函数。如果字符串是畸形的,它将抛出一个异常,并且“另外,如果您什么都不传入,则将从parseJSON返回一个空字符串、null或未定义的'null'。”浏览器提供JSON的本地实现。jQuery使用它来解析字符串"

#6


0  

JSON.parse will do the trick. Once parsed, you can push them into the array.

JSON。parse就可以。解析后,可以将它们推入数组。

var object = JSON.parse(param);
var array = [];
for(var i in object) {
   array.push(object[i]);
}

#1


76  

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本机解析器,因为它不仅比eval()快,而且更安全。

Native JSON parser is already available in:

本机JSON解析器已经在:

  • Firefox 3.5+
  • Firefox 3.5 +
  • IE 8+
  • IE 8 +
  • Opera 10.5+
  • Opera 10.5 +
  • Safari Safari 4.0.3+
  • Safari Safari 4.0.3 +
  • Chrome (don't know which version)
  • Chrome(不知道是哪个版本)

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.

Crockford在javascript上做了一个安全的回退,叫做json2。js,它是eval()方法的一种改进,添加了一些安全位,并使用本机JSON解析器API。您只需要包含该文件,删除它的第一行,并使用本地的JSON解析器,如果不存在json2,就可以完成这项工作。

Here is an example:

这是一个例子:

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

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:

一旦解析,就会得到一个带有属性a和b的对象,正如您可能知道的那样,您可以将对象看作是JavaScript中的散列表或关联数组,因此您将能够访问如下的值:

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]);
}

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中没有必要,但JSON规范要求对成员的键进行两次引用。所以navite解析器没有它就不能工作。如果我是你,我会添加它,但是如果不可能使用var myObject = eval("(" + myString + ")");的方法。

#2


7  

The simplest, but unsafe way to do it is:

最简单但不安全的方法是:

eval('(' + myJSONtext + ')')

But since this will interpret any javascript code, it has security holes. To protect against this use a json parser. If you're using a framework (jquery, mootools, etc.) there's a framework-specific call. Most of them are based on Douglas Crawford's parser available at http://www.json.org/js.html.

但是由于这将解释任何javascript代码,所以它有安全漏洞。要避免这种情况,请使用json解析器。如果您正在使用框架(jquery、mootools等),就会有一个特定于框架的调用。大多数解析器都基于Douglas Crawford的解析器,可以在http://www.json.org/js.html中找到。

#3


7  

Since your string is malformed JSON, a JSON parser can't parse it properly and even eval() will throw an error. It's also not an Array but a HashMap or simply an Object literal (malformed). If the Object literal will only contain number and string values (and no child objects/arrays) you can use the following code.

由于您的字符串是畸形的JSON, JSON解析器无法正确解析它,甚至eval()也会抛出一个错误。它也不是数组,而是HashMap,或者只是对象文字(畸形)。如果对象文字只包含数字和字符串值(没有子对象/数组),您可以使用以下代码。

function malformedJSON2Array (tar) {
    var arr = [];
    tar = tar.replace(/^\{|\}$/g,'').split(',');
    for(var i=0,cur,pair;cur=tar[i];i++){
        arr[i] = {};
        pair = cur.split(':');
        arr[i][pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
    }
    return arr;
}

malformedJSON2Array("{a:12, b:c, foo:bar}");
// result -> [{a:12},{b:'c'},{foo:'bar'}]

That code will turn your string into an Array of Objects (plural).

该代码将把字符串转换为对象数组(复数)。

If however you actually wanted a HashMap (Associative Array) and NOT an array, use the following code:

如果你想要一个HashMap(关联数组)而不是数组,请使用以下代码:

function malformedJSON2Object(tar) {
    var obj = {};
    tar = tar.replace(/^\{|\}$/g,'').split(',');
    for(var i=0,cur,pair;cur=tar[i];i++){
        pair = cur.split(':');
        obj[pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
    }
    return obj;
}

malformedJSON2Object("{a:12, b:c, foo:bar}");
// result -> {a:12,b:'c',foo:'bar'}

The above code will become a lot more complex when you start nesting objects and arrays. Basically you'd have to rewrite JSON.js and JSON2.js to support malformed JSON.

当开始嵌套对象和数组时,上面的代码将变得复杂得多。基本上你需要重写JSON。js和JSON2。js支持格式错误的JSON。

Also consider the following option, which is still bad I admit, but marginally better then sticking JSON inside an HTML tag's attribute.

还可以考虑下面的选项,我承认这仍然很糟糕,但比在HTML标记的属性中插入JSON要好一点。

<div id="DATA001">bla</div>
<!-- namespacing your data is even better! -->
<script>var DATA001 = {a:12,b:"c",foo:"bar"};</script>

I am assuming you omit quote marks in the string because you had put it inside an HTML tag's attribute and didn't want to escape quotes.

我假设您省略了字符串中的引号,因为您已经将它放在HTML标记的属性中,并且不希望转义引号。

#4


2  

You can use "for in"

你可以用for in

var myObject = {a:'12', b:'c', foo:'bar'};
var myArray = [];

for(key in myObject) {
    var value = myObject[key];
    myArray[key] = value;
}

myArray['a']; // returns 12

Notes: considering that myObject only have one level of key-value pairs.

注意:考虑到myObject只有一个级别的键-值对。

#5


1  

If you're using jQuery, there's the $.parseJSON() function. It throws an exception if the string is malformed, and "Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from parseJSON. Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string"

如果使用jQuery,可以使用$. parsejson()函数。如果字符串是畸形的,它将抛出一个异常,并且“另外,如果您什么都不传入,则将从parseJSON返回一个空字符串、null或未定义的'null'。”浏览器提供JSON的本地实现。jQuery使用它来解析字符串"

#6


0  

JSON.parse will do the trick. Once parsed, you can push them into the array.

JSON。parse就可以。解析后,可以将它们推入数组。

var object = JSON.parse(param);
var array = [];
for(var i in object) {
   array.push(object[i]);
}