简体   繁体   English

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

[英]Best way to convert string to array of object in javascript?

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?有什么好主意吗?

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.我认为这样做的最佳方式,正如Douglas Crockford (最伟大的 JavaScript 大师之一)在这里建议的那样,是使用JSON 原生解析器,因为它不仅比 eval() 更快,而且更安全。

Native JSON parser is already available in:本机 JSON 解析器已在以下版本可用:

  • Firefox 3.5+火狐 3.5+
  • IE 8+浏览器 8+
  • Opera 10.5+歌剧 10.5+
  • Safari Safari 4.0.3+野生动物园 野生动物园 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. Crockford 在 javascript 中做了一个安全的回退,称为json2.js ,它是 eval() 方法的一种改编,添加了一些安全位和本机 JSON 解析器 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.您只需要包含该文件,删除它的第一行,并使用本机 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:解析后,您将获得一个具有属性ab的对象,您可能知道,您可以将对象视为 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.最后,虽然在纯 JavaScript 中不是必需的,但JSON 规范需要双引号成员的键。 So the navite parser won't work without it.所以没有它 navite 解析器将无法工作。 If I were you I would add it, but if it is not possible use the var myObject = eval( "(" + myString + ")" );如果我是你,我会添加它,但如果不可能,请使用var myObject = eval( "(" + myString + ")" ); approach.方法。

Since your string is malformed JSON, a JSON parser can't parse it properly and even eval() will throw an error.由于您的字符串是格式错误的 JSON,因此 JSON 解析器无法正确解析它,甚至 eval() 也会抛出错误。 It's also not an Array but a HashMap or simply an Object literal (malformed).它也不是一个数组,而是一个 HashMap 或只是一个对象文字(格式错误)。 If the Object literal will only contain number and string values (and no child objects/arrays) you can use the following code.如果对象文字将只包含数字和字符串值(并且没有子对象/数组),您可以使用以下代码。

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.jsJSON2.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 标记的属性中并且不想转义引号。

The simplest, but unsafe way to do it is:最简单但不安全的方法是:

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

But since this will interpret any javascript code, it has security holes.但由于这将解释任何 javascript 代码,因此它存在安全漏洞。 To protect against this use a json parser.为了防止这种情况,请使用 json 解析器。 If you're using a framework (jquery, mootools, etc.) there's a framework-specific call.如果您使用的是框架(jquery、mootools 等),则会有特定于框架的调用。 Most of them are based on Douglas Crawford's parser available at http://www.json.org/js.html .其中大部分基于 Douglas Crawford 的解析器,网址为http://www.json.org/js.html

You can use "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 只有一层键值对。

JSON.parse will do the trick. JSON.parse 可以解决问题。 Once parsed, you can push them into the array.解析后,您可以将它们推入数组。

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

If you're using jQuery, there's the $.parseJSON() function.如果您使用的是 jQuery,则可以使用$.parseJSON()函数。 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"如果字符串格式错误,它会抛出异常,并且“此外,如果你什么都不传入,空字符串、null 或 undefined,'null' 将从 parseJSON 返回。浏览器提供 JSON.parse 的本机实现,jQuery用它来解析字符串”

Use safe evaluation.使用安全评估。 Unlike JSON.parse, this doesn't require the keys or values to be quoted.与 JSON.parse 不同,这不需要引用键或值。 Quote values only if they contain embedded commas.仅当它们包含嵌入的逗号时才引用值。

const myStr = "{a:1, b:2, c:3}";
const myObj = string_exp(myStr);
console.log("dot: " + myObj.c);

function string_exp(sCmd) {
    return Function(`'use strict'; return (${sCmd})`)();
}

https://dev.to/spukas/everything-wrong-with-javascript-eval-35on#:~:text=the%20variable%20exists.-,Alternatives,-The%20most%20simple https://dev.to/spukas/everything-wrong-with-javascript-eval-35on#:~:text=the%20variable%20exists.-,Alternatives,-The%20most%20simple

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM