0

how can i add comma after each object and convert into array. here's my response data

{"url":"example.com/john","age":"32"}{"url":"example.com/mike","age":"42"}

i want this

[{"url":"example.com/john","age":"32"},{"url":"example.com/mike","age":"42"}]

i tried with regex but it's converting data into string but i want to render this data

4
  • Are the response objects plain text (string)? Because otherwise I don't know how you can get 2 objects that aren't in array. Commented Aug 7, 2022 at 18:13
  • yes it's plain text Commented Aug 7, 2022 at 18:21
  • You can converting data into string with regex, and then use JSON.parse(text) to convert it to the array. Commented Aug 7, 2022 at 18:24
  • 1
    Yeah but that's not valid json Commented Aug 7, 2022 at 18:24

1 Answer 1

2

How about a little bit of Regex magic to make it valid JSON.

const res = '{"url":"example.com/john","age":"32"}{"url":"example.com/mike","age":"42"}';

const betterJson = `[${res.replace(/}{/g,'},{')}]`;
console.log(JSON.parse(betterJson))

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

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.