Separate a simple JSON structure using a regular expression

I have never used a regex before, and I want to split a file with one or more JSON objects, JSON objects are not comma separated. So I need to break them between "} {" and keep both curly braces. This is what the line looks like:

{id:"123",name:"myName"}{id:"456",name:"anotherName"} 

I need an array of strings, e.g. using string.split()

 ["{id:"123",name:"myName"}", "{"id:"456",name:"anotherName"}"] 
+7
source share
1 answer

If your objects are no more complicated than you show, you can use the images as follows:

 String[] strs = str.split("(?<=\\})(?=\\{)"); 

Example:

 String str = "{id:\"123\",name:\"myName\"}{id:\"456\",name:\"yetanotherName\"}{id:\"456\",name:\"anotherName\"}"; String[] strs = str.split("(?<=\\})(?=\\{)"); for (String s : strs) { System.out.println(s); } 

prints

 {id:"123",name:"myName"} {id:"456",name:"anotherName"} {id:"456",name:"yetanotherName"} 

If your objects are more complex, the regex probably won't work, and you have to parse your string.

+11
source

All Articles