json - Javascript Convert String to Array of Objects -


i have nodejs app accepts a string (uploaded input!) have no control on input merely building rest service processes data.

that string meant array of json objects can loop through extract each element ...

i'm receiving following (as string):

[   {name: 'jane',        id: '005b0000000mga7aag'},   {name: 'tom',        id: '005b0000000mga7aaf'} ] 

when try json.parse get

syntaxerror: unexpected token n 

understandably so, because know invalid json

whereas this next string valid json , passes http://jsonlint.com/:

[     {"name": "jack",         "id": "005b0000000mga7aaa"},     {"name": "jill",         "id": "005b0000000mga7aab"} ] 

my question is: how can accept first input , parse allow:

parsed[0]['name'] == 'jane' >> true 

my first instinct string replace keys (e.g. name "name") , try parsing it. if else has solution, i'd grateful.

you can bit of regex replacing:

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 wrap propertie names quotes, replace single-quotes double-quotes. enough make valid json can parsed.

here working example


note: using regex in general things not ideal, , solution work under specific circumstances (like example). mentioned in comments, 1 problem if data values contained colon :

with in mind, 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 match variables (alphanumeric) end colon :, ingore matches found between quotes (i.e. data string values)

here example


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -