Javascript 在javascript中将字符串转换为对象数组的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3473639/
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
Best way to convert string to array of object in javascript?
提问by Zeck
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?
如何将此字符串转换为对象数组?有什么好主意吗?
回答by alcuadrado
I think that the best way of doing this, as Douglas Crockford(one of the biggests gurus of JavaScript) suggests in hereis using the JSON native parser, as it is not only faster than the eval(), it's also more secure.
我认为最好的方法是使用JSON native parser,正如Douglas Crockford(JavaScript 的最大大师之一)在这里建议的那样,它不仅比 eval() 更快,而且更安全。
Native JSON parser is already available in:
本机 JSON 解析器已在以下位置可用:
- Firefox 3.5+
- IE 8+
- Opera 10.5+
- Safari Safari 4.0.3+
- Chrome (don't know which version)
- 火狐 3.5+
- 浏览器 8+
- 歌剧 10.5+
- Safari Safari 4.0.3+
- 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 aand b, and as you may know, you can treat an object as a hash table or associative arrayin 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 specrequires 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 + ")" );方法。
回答by BGerrissen
Since your string is malformedJSON, 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.jsand JSON2.jsto 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.
还要考虑以下选项,我承认这仍然很糟糕,但比将 JSON 粘贴在 HTML 标签的属性中要好一些。
<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 标记的属性中并且不想转义引号。
回答by Rob
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 获得。
回答by Topera
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 只有一层键值对。
回答by jamiebarrow
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()函数。如果字符串格式错误,它会抛出异常,并且“此外,如果你什么都不传入,一个空字符串、null 或未定义,将从 parseJSON 返回 'null'。浏览器提供 JSON.parse 的本机实现,jQuery用它来解析字符串”
回答by Sarathi S
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]);
}

