繁体   English   中英

ionic 2从格式错误的json获取数据

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

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