Home > front end >  splitting json string by accolade and keep the accolade
splitting json string by accolade and keep the accolade

Time:11-21

I want to do a split by "{" and keep the "{".

The result should be an array:

[
"{  \""text\" : \"alinea 1\", \"type\" : \"paragraph\"  }",
"{  \""text\" : \"alinea 2\", \"type\" : \"paragraph\"  }"
]

The code I have got so far:

("{    \"text\": \"alinea 1\",    \"type\": \"paragraph\"  },  {    \"text\": \"alinea2\",    \"type\": \"paragraph\"  }").split(/([?={?>={] )/g)

But the output is not as expected:

enter image description here

I am not a hero with regex... and tried to fiddle a bit with this: Javascript and regex: split string and keep the separator

CodePudding user response:

Please fix on server or wrap in [] before using JSON.parse to get what I expect you actually wanted

const str = `{    \"text\": \"alinea 1\",    \"type\": \"paragraph\"  },  {    \"text\": \"alinea2\",    \"type\": \"paragraph\"  }`
console.log(JSON.parse(`[${str}]`))

CodePudding user response:

Obviously in a production situation you probably want to use native JSON operations but as an exercise you could do something like this, which seems pretty close to what you were asking for. (Note that the positive lookahead used here is pretty terrible, since it happily matches an empty string. Change the ,? to (?:(,|$)) to make it arguably less terrible)

NOTE: JSON is not a regular language. Using regular expressions to parse it is asking for a visit from Zalgo.

input = "{    \"text\": \"alinea 1\",    \"type\": \"paragraph\"  },  {    \"text\": \"alinea2\",    \"type\": \"paragraph\"  }"

pattern = /(?<obj>{[^}]*})(?=\s*(?:,?))/g
output = [...input.matchAll(pattern)].map( match => match.groups.obj )
console.log(output)

  • Related