2017-10-10 57 views
0

我有一個響應對象,它看起來是這樣的 -解析JSON字符串響應。已經嘗試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

+2

您的位置屬性是字符串。 –

+0

它在哪裏變得不明確? –

+4

是的,不認爲有效json –

回答

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

+0

修復了後端。現在獲得正確的響應,這是一個有效的JSON - {「country」:「Poland」,「latitude」:51.9667,「longitude」:19.7333}。感謝您的建議。如果後端發送不正確的響應並且無法控制它,這也會有所幫助 –

+1

解決源代碼問題確實是更好的選擇。我假設你不能:) –

+0

'/([A-Za-z] +)/ g'是否以同樣的方式工作? –

1

值的location屬性裏面是不是有效的JSON。 JSON.parse因此而失敗。您將需要以下內容:

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

請注意屬性和字符串值如何被" s包圍。

+0

什麼是downvote?我唯一能想到的就是這被認爲是明顯的重複,但我沒有看到任何投票結束...... –

+0

不確定誰downvoted和什麼。修復後端。現在獲得正確的響應,這是一個有效的JSON - {「country」:「Poland」,「latitude」:51.9667,「longitude」:19.7333}。感謝您的建議。 –