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?

Adam Griffiths
  • 680
  • 6
  • 26
  • 60

3 Answers3

7

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.

KevBot
  • 17,900
  • 5
  • 50
  • 68
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%; }
gyre
  • 16,369
  • 3
  • 37
  • 47
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;
});
9000
  • 39,899
  • 9
  • 66
  • 104