0

I have a json assigned to variable as:

var a = "[{a:123}]";

Now if I do a[0] it gives result as [. On doing a = JSON.parse(a) it gives error as Uncaught SyntaxError: Unexpected token a in JSON at position 2

How can i convert a into a = [{a:123}]; ?

2
  • 6
    That's because the object in the array is not valid JSON. Now if it was this var a = '[{"a":123}]' it would work. Try using a JSON Validator Commented Feb 21, 2017 at 10:41
  • jsonlint.com Commented Feb 21, 2017 at 10:43

2 Answers 2

3

The problem here is that you don't have a valid JSON.

Uncaught SyntaxError: Unexpected token a in JSON at position 2

This error complains about the character "a" which is not valid here. See http://www.json.org/

You could in theory achieve your goal by using eval but this is highly insecure because you can evaluate any code that is present in your string so I wouldn't recommend that.

You have to either make sure that the JSON you get is valid, or you may need to preprocess the string before passing it to JSON.parse if the format cannot be changed.

By the way, contrary to another answer here that was upvoted for some reason, there is no such thing as Array.parse:

$ node -e 'Array.parse()'
[eval]:1
Array.parse()
      ^    
TypeError: Array.parse is not a function

See also:

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

Comments

0

You have to replace :

var a = "[{a:123}]";

by :

var a = "[{\"a\":123}]";

1 Comment

Yes this worked for me, i changed the data query which was building the object. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.