Javascript Convert string to array of objects

I have a NodeJS application that accepts a string (loaded input!). I have no control . I just create a REST service to process the data.

This line is for Array JSON objects , after which I can execute a loop to extract each element ...

I get the following (as a string):

[ {Name: 'Jane', Id: '005b0000000MGa7AAG'}, {Name: 'Tom', Id: '005b0000000MGa7AAF'} ] 

When I try JSON.parse , I get

 SyntaxError: Unexpected token N 

Understood, because I know this is Invalid JSON

whereas this next line is valid JSON and passes http://jsonlint.com/ :

 [ {"Name": "Jack", "Id": "005b0000000MGa7AAA"}, {"Name": "Jill", "Id": "005b0000000MGa7AAB"} ] 

My question is: how can I accept the first input and parse it to resolve:

 parsed[0]['Name'] == 'Jane' >> true 

My first instinct is for the string to replace the keys (for example, Name with "Name"), and then try to parse it. But if anyone else has a solution, I will be grateful.

+7
source share
2 answers

You can do this by replacing the regex:

 var json = "[ {Name: 'Jane', Id: '005b0000000MGa7AAG'}, {Name: 'Tom', Id: '005b0000000MGa7AAF'} ]"; var newJson = json.replace(/([a-zA-Z0-9]+?):/g, '"$1":'); newJson = newJson.replace(/'/g, '"'); var data = JSON.parse(newJson); alert(data[0]["Name"]); 

First of all, we end the property names with quotes, then we replace single quotes with double quotes. This is enough to make it valid JSON, which can then be parsed.

Here is a working example


NOTE Using RegEx in general for such things is not ideal, and this solution will only work under certain circumstances (for example, in this example). As mentioned in the comments, one problem would be if the data values ​​contained a colon :

With this in mind, this is a more reliable solution:

 var json = $("div").html(); var newJson = json.replace(/'/g, '"'); newJson = newJson.replace(/([^"]+)|("[^"]+")/g, function($0, $1, $2) { if ($1) { return $1.replace(/([a-zA-Z0-9]+?):/g, '"$1":'); } else { return $2; } }); var data = JSON.parse(newJson); alert(data[0]["Name"]); 

This will match any variables (alphanumeric) ending with a colon : but will contain any matches found between quotation marks (i.e. data string values)

Here is an example

+7
source

Create a javascript class, fill the object with your input, and then convert it to pure json using: JSON.stringify(object) to avoid errors. My full post is here .

NOTE. If you are using IE7 or less, you must add the JSON.js library to use the JSON.stringify() function.

+1
source

All Articles