0

I have the following text object:

[{message="Hello World"}]

How can I convert this to a JavaScript Array?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

yes, i just came back to edit the question to state that's it JSON, not HTML. Your solution worked perfectly. Thank you.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.