简体   繁体   中英

How can I convert a JSON text Array to a JavaScript Array?

I have the following text object:

[{message="Hello World"}]

How can I convert this to a JavaScript Array?

You could replace the = with a : and then use JSON.parse. Then you'd need to wrap the message with " 's.

// error = not :
JSON.parse('[{message="Hello World"}]')

// errors = message not "message"
JSON.parse('[{message="Hello World"}]'.replace('=',':'))

Try this:

var message = '[{message="Hello World"}]'
message = message.replace('message', '"message"').replace('=',':')
JSON.parse(message)

You can use eval to do the same:

// still gotta replace the '='
eval('[{message="Hello World"}]'.replace("=",":"))

But eval has other problems:

eval('window.alert("eval is evil")')

So be careful. Make sure you know what you're eval'ing.

That's JSON . If you're using jquery, then

var arr = jQuery.parseJSON('[{message="Hello World"}]');
alert(arr[0].message);

A far less 'safe' method is

var arr = eval('[{message="Hello World"}]');

after which arr will be the same as the jquery version.

However, it should probably be [{message:"Hello World"}] to be proper valid json.

Although this is not valid JSON, you could replace all = with : , add quotes to keys, and then convert it using JSON.parse :

//text = '[{message="Hello World"}]'
text = text.replace(/(\w+)\s*=/g, "\"$1\":");
var array = JSON.parse(text);

If JSON.parse is not supported, you could use eval :

//text = '[{message="Hello World"}]'
text = text.replace(/(\w+)\s*=/g, "\"$1\":");
var array = eval("("+text+")");

Although that is not recommended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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