1

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'}];
4
  • 1
    You should change the string to be valid JSON. Commented Dec 4, 2013 at 1:09
  • 1
    Where do you get that string? You can surround it in [] (by concatenation) then JSON.parse() it if you're sure the rest is properly formed. ( it isn't though, as the properties href are not quoted) Commented Dec 4, 2013 at 1:10
  • You would need to do something like this.. JSON.parse('[' + '{"href":"one"},{"href":"two"}' + ']') But why not construct it properly at the start itself rather than postprocessing some invalid JSON. Commented Dec 4, 2013 at 1:12
  • 1
    also new is a keyword and cannot be used as the name of a variable.. Commented Dec 4, 2013 at 1:19

4 Answers 4

3

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)

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)

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

2 Comments

If it could be modified to be a bit more like JSON, hopefully it could be modified to be JSON and be an array to begin with.
@MichaelBerkowski of'course :) i am just being easy on the OP
1

If you could modify the original string to be valid JSON then you could do this:

JSON.parse(test)

Valid JSON:

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

Comments

1

Using jQuery:

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

jsonObj is your JSON object.

1 Comment

no need for jQuery. The JSON is natively supported in all browsers nowadays.. caniuse.com/json
1

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:

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.

As an extremely trivial example, consider this

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

Bam, jQuery is wiped out.

Demonstrated here

1 Comment

But be careful about where the input is coming from.

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.