1

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: enter image description here

The issue is when I loop through this array to access titles separately, I get it as undefined.

Any recommendations would be appreciated

3
  • 4
    Do you have control over the input string? If you make a couple of amendments it could be made in to valid JSON which can be parsed in a single call to JSON.parse() Commented Sep 8, 2020 at 19:13
  • Yes I can change the string format, @Ro Commented Sep 8, 2020 at 19:16
  • 1
    Since you have the ability to change it, change it to: [{"title":"XYZ","id":"123"},{"title":"NPS","id":"124"},{"title":"LMW","id":"125"}] then you can just use JSON.parse(str) Commented Sep 8, 2020 at 19:19

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2
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"]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.