简体   繁体   English

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

[英]ionic 2 get data from malformed json

is there anyway i can get this malformed json format which is odd i have no control over this json manually so i need to get this data and manipulate it with rxjs observable from http get 无论如何,我可以获得这种格式错误的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"
}

I tried with your JSON in the console and this seems to work. 我在控制台中尝试使用您的JSON,这似乎可行。 In the map function I've used you can probably implement more generic replacement methods to alter the strings, but it works for this example. 在我使用的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 
}

Take the JSON data you've posted up there and copy it to a variable as a string and test the function, it will return a properly formatted array of JSON data. 拿走您在那里发布的JSON数据,并将其作为字符串复制到变量中并测试该函数,它将返回格式正确的JSON数据数组。

Call that when you get a response from your service to transform the data. 当您从服务获得响应以转换数据时调用该函数。 As far as the observable chains and any async issues you might be seeing those are separate things. 至于可观察的链和任何异步问题,您可能会发现它们是分开的。 This function is just designed to convert your malformed JSON. 此函数仅用于转换格式错误的JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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