How can I convert a JSON text Array to a JavaScript Array?
I have the following text object:
[{messa开发者_如何学Cge="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.
精彩评论