3

I have the following variable (given to me through a HTTP response, hence the string):

var result = '[{name: "John"}, {name: "Alice"}, {name: "Lily"}]'

In reality there are more objects and each object has more properties, but you get the idea.

When trying JSON.parse(result) I get the following error:

[{name: "John"}, {name: "Alice"}, {name: "Lily"}]
  ^

SyntaxError: Unexpected token n

How can I parse this string into an array of javascript objects?

3
  • 3
    it's not a valid JSON Commented Mar 30, 2017 at 15:16
  • 1
    keys should be in quotes like [{"name": "John"}... Commented Mar 30, 2017 at 15:18
  • you could do var result = eval(yourString); if you really don't care about the downsides Commented Mar 30, 2017 at 15:32

3 Answers 3

6

This is not valid JSON. In order for it to be valid JSON, you would need to have quotes around the keys ("name")

[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]

The error occurs because the parser does not hit a " and instead hits the n.

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

Comments

1

Since your string is not valid JSON (it lacks quotes around property keys), you cannot parse it using JSON.parse. If you can control the response, you should change it to return:

[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]


Working Demo:

var result = '[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]'

console.log(JSON.parse(result))
.as-console-wrapper { min-height: 100%; }

Comments

0

Since your input format is rigid, parsing is trivial.

function cutSides(s) { return s.substring(1, s.length - 1); }
var pairs = cutSides(result).split(', ');
var list_of_objects = pairs.map(function(s) { 
    var pair = cutSides(s).split(': ');
    var result = {};
    result[pair[0]] = cutSides(pair[1]); 
    return result;
});

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.