简体   繁体   中英

parsing a JSON string response. Already tried JSON.parse()

I have a response object that looks something like this -

{  
location: '{country:Poland,latitude:50.0575,longitude:19.9802}',
ip: '83.26.234.177',
name: 'John Doe'   
}

I am trying to read the country name like this -

data.forEach(function(datapoint) {
    dataObject.ip = datapoint.ip;
    var locationObject = datapoint.location; // also tried JSON.parse
    console.log(locationObject); //{country:Poland,latitude:50.0575,longitude:19.9802}
    console.log(locationObject.country); // undefined
    console.log(locationObject.latitude); //undefined
    console.log(locationObject.longitude); //undefined
}

getting undefined .

datapoint.location is a not valid json. Use String#replace to convert it to a valid json string and then parse:

 var data = [{ location: '{country:Poland,latitude:50.0575,longitude:19.9802}', ip: '83.26.234.177', name: 'John Doe' }]; data.forEach(function(datapoint) { var json = datapoint.location.replace(/([^\\d\\.{}:,]+)/g, '"$1"'); // wrap the keys and non number values in quotes var locationObject = JSON.parse(json); console.log(locationObject.country); console.log(locationObject.latitude); console.log(locationObject.longitude); }); 

The value inside of your location property is not valid JSON. JSON.parse fails because of that. You would need the following:

'{"country":"Poland","latitude":50.0575,"longitude":19.9802}'

Note how the properties and string values are surrounded with " s.

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