无论如何我可以得到这种格式错误的json格式,这是奇怪的我手动无法控制这个json所以我需要获取这些数据并使用rxjs observable从http获取
{
"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"
}
答案 0 :(得分:0)
我在控制台中尝试使用您的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。