簡體   English   中英

解析JSON字符串響應。 已經嘗試過JSON.parse()

[英]parsing a JSON string response. Already tried JSON.parse()

我有一個看起來像這樣的響應對象-

{  
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

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); }); 

location屬性中的值是無效的JSON。 JSON.parse失敗。 您將需要以下內容:

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

請注意,屬性和字符串值如何用"括起來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM