在javascript中将字符串转换为对象数组的最佳方法?
我想将下面的字符串转换为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我认为最好的方法是这样做,正如Douglas Crockford(JavaScript 最伟大的大师之一)建议此处使用 JSON 原生解析器,因为它不仅比 eval() 更快,而且更安全。
本机 JSON 解析器已可用于:
Crockford 在 javascript 中做了一个安全的后备,称为 json2.js,这是 eval() 方法的改编,添加了一些安全位以及原生 JSON 解析器 API。您只需要包含该文件,删除其第一行,然后使用本机 JSON 解析器,如果它不存在,则 json2 将完成这项工作。
这是一个示例:
解析后,您将获得一个具有属性
a
和b
的对象,正如您可能知道的,您可以将对象视为哈希表或 < a href="http://en.wikipedia.org/wiki/Associative_array" rel="noreferrer">关联数组 在 JavaScript 中,这样你就可以像这样访问值:如果你只想要一个简单数组而不是关联数组,您可以执行以下操作:
最后,尽管在纯 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:
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:
Once parsed you'll get an object with attributes
a
andb
, 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:If you just want a simple array and not an associative one you could do something like:
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.由于您的字符串是格式错误 JSON,因此 JSON 解析器无法正确解析它,甚至 eval() 也会抛出错误。它也不是一个数组,而是一个 HashMap 或只是一个对象文字(格式错误)。如果对象文字仅包含数字和字符串值(并且没有子对象/数组),则可以使用以下代码。
该代码会将您的字符串转换为对象数组(复数)。
然而,如果您实际上想要一个 HashMap(关联数组)而不是数组,请使用以下代码:
当您开始嵌套对象和数组时,上述代码将变得更加复杂。基本上你必须重写 JSON.js 和 JSON2.js 支持格式错误的 JSON。
还要考虑以下选项,我承认这仍然很糟糕,但比将 JSON 粘贴到 HTML 标记的属性中要好一些。
我假设您省略了字符串中的引号,因为您已将其放入 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.
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:
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.
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.
最简单但不安全的方法是:
但由于这会解释任何 JavaScript 代码,因此它存在安全漏洞。为了防止这种情况,请使用 json 解析器。如果您使用框架(jquery、mootools 等),则会有一个特定于框架的调用。其中大多数基于 Douglas Crawford 的解析器,可在 http://www.json.org/js.html< /a>.
The simplest, but unsafe way to do it is:
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.
可以使用“for in”
注意:考虑到myObject只有一层键值对。
You can use "for in"
Notes: considering that myObject only have one level of key-value pairs.
JSON.parse 就可以了。解析后,您可以将它们推入数组中。
JSON.parse will do the trick. Once parsed, you can push them into the array.
如果您使用的是 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"
使用安全评估。与 JSON.parse 不同,这不需要引用键或值。仅当值包含嵌入的逗号时才用引号引起来。
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.
https://dev.to/spukas/everything-wrong-with-javascript-eval-35on#:~:text=the%20variable%20exists.-,Alternatives,-The%20most%20simple