简体   繁体   English

如何在js中转换为数组?

[英]how to convert to array in js?

I have this string which I want to convert to an array: 我有这个要转换为数组的字符串:

var test = "{href:'one'},{href:'two'}";

So how can I convert this to an array?: 那么如何将其转换为数组?:

var new = [{href:'one'},{href:'two'}];

It depends where you got it from.. 这取决于你从哪里得到的。

If possible you should correct it a bit to make it valid JSON syntax ( at least in terms of the quotes ) 如果可能的话,您应该对其进行一些纠正以使其成为有效的JSON语法( 至少在引号方面

var test  = '{"href":"one"},{"href":"two"}';
var arr = JSON.parse('[' + test + ']');

Notice the " around both keys and values. 注意键和值周围的"

( making directly var test = '[{"href":"one"},{"href":"two"}]'; is even better ) 直接进行var test = '[{"href":"one"},{"href":"two"}]';甚至更好

If you could modify the original string to be valid JSON then you could do this: 如果您可以将原始字符串修改为有效的JSON,则可以执行以下操作:

JSON.parse(test)

Valid JSON: 有效的JSON:

var test  = '[{"href":"one"},{"href":"two"}]';

If changing the string to be valid JSON is not an option, and you fully trust this string, and its origin then I would use eval: 如果不能将字符串更改为有效的JSON, 并且您完全信任此字符串及其来源,则可以使用eval:

var test = "{href:'one'},{href:'two'}";
var arr = eval("[" + test + "]");

On that last note, please be aware that, if this string is coming from the user, it would be possible for them to pass in malicious code that eval will happily execute. 在这最后一个音符,请注意,如果这个字符串是从用户的到来,将有可能为他们的恶意代码通过eval会很乐意执行。

As an extremely trivial example, consider this 作为一个非常琐碎的例子,考虑一下

var test = "(function(){ window.jQuery = undefined; })()";
var arr = eval("[" + test + "]");

Bam, jQuery is wiped out. Bam,jQuery被淘汰了。

Demonstrated here 在这里展示

Using jQuery: 使用jQuery:

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');

jsonObj is your JSON object. jsonObj是您的JSON对象。

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

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