-2

If I have a string like below:

[{"id":123, "name": "Sally", "age": 36}
{"id":138, "name": "Nicholas", "age": 48}
{"id":194, "name": "Steven", "age": 25}]

Is there a way for me to convert it to object? Since, their format is pretty much the same. Do correct me and let me know if I am wrong. Thank you.

str
  • 42,689
  • 17
  • 109
  • 127
CloudSeph
  • 863
  • 4
  • 15
  • 36

1 Answers1

0

You have not valid json, you can add , if you creating this by your own

[{"id":123, "name": "Sally", "age": 36} // no , not valid
{"id":138, "name": "Nicholas", "age": 48} // no , not valid
{"id":194, "name": "Steven", "age": 25}]

[{"id":123, "name": "Sally", "age": 36}, // <- you need , here
{"id":138, "name": "Nicholas", "age": 48}, // <- you need , here
{"id":194, "name": "Steven", "age": 25}]

But If get this string from somewhere, you can add , before doing JSON.parse and make your string a valid json.

var a = `[{"id":123, "name": "Sally", "age": 36}
{"id":138, "name": "Nicholas", "age": 48}
{"id":194, "name": "Steven", "age": 25}]`

var b = JSON.parse(a.replace(/\n/gim, ','));
console.log (b)
qiAlex
  • 4,290
  • 2
  • 19
  • 35
  • I don't understand how you were able to post an answer after it was closed as a duplicate. In any case, it doesn't matter if he had commas or not. It would seem it was a typo as the OP clearly thanked adeneo for the answer in the comments. – kemicofa ghost Aug 16 '17 at 09:42