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

发布于 2024-09-14 11:54:00 字数 115 浏览 7 评论 0原文

我想将下面的字符串转换为 JavaScript 中的数组。

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

过期以后 2024-09-21 11:54:00

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

本机 JSON 解析器已可用于:

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

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

这是一个示例:

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

解析后,您将获得一个具有属性 ab 的对象,正如您可能知道的,您可以将对象视为哈希表或 < a href="http://en.wikipedia.org/wiki/Associative_array" rel="noreferrer">关联数组 在 JavaScript 中,这样你就可以像这样访问值:

myObject['a'];

如果你只想要一个简单数组而不是关联数组,您可以执行以下操作:

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

最后,尽管在纯 JavaScript 中没有必要,但 JSON 规范 要求双引号成员的键。所以如果没有它 navite 解析器就无法工作。如果我是你,我会添加它,但如果不可能,请使用 var myObject = eval( "(" + myString + ")" ); 方法。

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.

Native JSON parser is already available in:

  • Firefox 3.5+
  • IE 8+
  • Opera 10.5+
  • Safari Safari 4.0.3+
  • Chrome (don't know which version)

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.

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:

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.

我不在是我 2024-09-21 11:54:00

由于您的字符串是格式错误 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'}]

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

然而,如果您实际上想要一个 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'}

当您开始嵌套对象和数组时,上述代码将变得更加复杂。基本上你必须重写 JSON.jsJSON2.js 支持格式错误的 JSON。

还要考虑以下选项,我承认这仍然很糟糕,但比将 JSON 粘贴到 HTML 标记的属性中要好一些。

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

我假设您省略了字符串中的引号,因为您已将其放入 HTML 标记的属性中并且不想转义引号。

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.

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:

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.

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

<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.

玩套路吗 2024-09-21 11:54:00

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

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

但由于这会解释任何 JavaScript 代码,因此它存在安全漏洞。为了防止这种情况,请使用 json 解析器。如果您使用框架(jquery、mootools 等),则会有一个特定于框架的调用。其中大多数基于 Douglas Crawford 的解析器,可在 http://www.json.org/js.html< /a>.

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.

琉璃繁缕 2024-09-21 11:54:00

可以使用“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

注意:考虑到myObject只有一层键值对。

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.

失眠症患者 2024-09-21 11:54:00

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

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

JSON.parse will do the trick. 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]);
}
惜醉颜 2024-09-21 11:54:00

如果您使用的是 jQuery,则可以使用 $.parseJSON() 函数。如果字符串格式错误,它会抛出异常,并且“此外,如果您不传入任何内容、空字符串、null 或未定义,'null' 将从 parseJSON 返回。其中浏览器提供 JSON.parse、jQuery 的本机实现用它来解析字符串”

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"

孤寂小茶 2024-09-21 11:54:00

使用安全评估。与 JSON.parse 不同,这不需要引用键或值。仅当值包含嵌入的逗号时才用引号引起来。

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.-,替代方案,-%20most%20simple

Use safe evaluation. Unlike JSON.parse, this doesn't require the keys or values to be quoted. 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文