[英]ionic 2 get data from malformed json
無論如何,我可以獲得這種格式錯誤的json格式,這很奇怪,我無法手動控制此json,所以我需要獲取此數據並使用可從http get觀察到的rxjs對其進行操作
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
我在控制台中嘗試使用您的JSON,這似乎可行。 在我使用的map函數中,您可能可以實現更通用的替換方法來更改字符串,但是它適用於本示例。
function fixBadJSON(response){
let badJSON = JSON.stringify(response); // added this edit in case you don't know how to get the response to a string
let arr = badJSON.split('}\n'); // Looks like the JSON elements are split by linefeeds preceded by closing bracket, make into arr length of 3
let fixedArr = arr.map((item)=>{ // map the array to another, replace the comma at the end of the avatarImage key. elements in array should be proper JSON
if(item[item.length] != '}') item += '}'; //put the brackets back at thend of the string if they got taken out in the split, probably a better way to handle this logic with regex etc
return item.replace('jpg",','jpg"')
});
let parsedJSON = JSON.parse(JSON.stringify(fixedArr));
return parsedJSON
}
拿走您在那里發布的JSON數據,並將其作為字符串復制到變量中並測試該函數,它將返回格式正確的JSON數據數組。
當您從服務獲得響應以轉換數據時調用該函數。 至於可觀察的鏈和任何異步問題,您可能會發現它們是分開的。 此函數僅用於轉換格式錯誤的JSON。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.