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

时间:2017-10-10 21:04:20

标签: javascript json node.js object

我有一个看起来像这样的响应对象 -

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

我试图像这样阅读国家名称 -

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
}

获取undefined

2 个答案:

答案 0 :(得分:1)

datapoint.location是无效的json。使用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);
});




答案 1 :(得分:1)

location属性中的值无效JSON。 JSON.parse因此而失败。您需要以下内容:

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

请注意属性和字符串值是如何被"包围的。