1

I have an input Json string like this:

var x= "[{\"name\":\"ahmed\",\"age\":\"26\"}, 
{\"name\":\"Sam\",\"age\":\"25\"}]"

I want to split it to a list of strings from{ to } as follows without removing a delimiter

var list;
 list[0]= {\"name\":\"ahmed\",\"age\":\"26\"}
 list[1]= {\"name\":\"Sam\",\"age\":\"25\"}

using the split method removes the delimiter and does not yield the correct format

x= x.replace(/\[\/]/g, '/'); //to remove [ and ]
x= x.replace(  /},/ ,'}\n' ); // does not split the string to list of strings
list = x; // type mismatch error since x is a string and list is array
User MA
  • 21
  • 1
  • 8
    How about parsing the JSON using JSON.parse? – Teemu Nov 13 '18 at 09:51
  • Possible duplicate of [JS string.split() without removing the delimiters](https://stackoverflow.com/questions/4514144/js-string-split-without-removing-the-delimiters) – pwolaq Nov 13 '18 at 09:57
  • @Teemu thanks alot.. don't know how this didn't cross my mind... – User MA Nov 13 '18 at 10:00

3 Answers3

1

As commented above by Teemu, using JSON.parse is the safe and correct way to parse json.

const x = "[{\"name\":\"ahmed\",\"age\":\"26\"},{\"name\":\"Sam\",\"age\":\"25\"}]";

console.log(JSON.parse(x));
David Lemon
  • 1,560
  • 10
  • 21
1

You can parse it to JSON first then use map to make list out of it.

var parsedX = JSON.parse(x);
var list = parsedX.map(x => JSON.stringify(x).replace(/"/g,'\\"'));
qiAlex
  • 4,290
  • 2
  • 19
  • 35
ptdien
  • 84
  • 4
0

You could use following code to achieve desired result with this particular type of json:

var str = "[{\"name\":\"ahmed\",\"age\":\"26\"}, {\"name\":\"Sam\",\"age\":\"25\"}]";
var list = str.match(/[{][^{}]*[}]/gm);

alert(list)

Fell free to ask if you have any questions:

Tornike Shavishvili
  • 1,244
  • 4
  • 16
  • 35