I have a string formatted as below:
{"title":"XYZ","id":"123"} {"title":"NPS","id":"124"}{"title":"LMW","id":"125"}
I am trying to convert this into an array by storing it in a variable and splitting it as such:
let prodInfo = "{"title":"XYZ","id":"123"} {"title":"NPS","id":"124"}{"title":"LMW","id":"125"}";
I then split this variable as in:
let infoArry = prodInfo.split("}");
console.log(infoArry);
The results I get after this is:
The issue is when I loop through this array to access titles separately, I get it as undefined.
Any recommendations would be appreciated
Given that you state in the comments under the question that you are able to change the input string format, I would strongly suggest you convert it to valid JSON. Then you can simply call JSON.parse()
and work with the resulting array as needed. Try this:
var input = '[{"title":"XYZ","id":"123"},{"title":"NPS","id":"124"},{"title":"LMW","id":"125"}]'; var output = JSON.parse(input); output.forEach(obj => console.log(obj.title)); // just an example
const input = '{"title":"XYZ","id":"123"} {"title":"NPS","id":"124"}{"title":"LMW","id":"125"}'; const objects = input.split("}").filter(element => !!element).map(element => JSON.parse(element + "}"));; objects.forEach(object => console.log(object["title"]));
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.