简体   繁体   中英

Javascript convert stringified array of objects into array of objects

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?

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 .

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%; } 

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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM