简体   繁体   English

解析JSON字符串响应。 已经尝试过JSON.parse()

[英]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 . 变得undefined

datapoint.location is a not valid json. datapoint.location是无效的json。 Use String#replace to convert it to a valid json string and then parse: 使用String#replace将其转换为有效的json字符串,然后进行解析:

 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. location属性中的值是无效的JSON。 JSON.parse fails because of that. JSON.parse失败。 You would need the following: 您将需要以下内容:

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

Note how the properties and string values are surrounded with " s. 请注意,属性和字符串值如何用"括起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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