简体   繁体   中英

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

{
  "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. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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