10

I've never used a regex before and I am looking to split up a file that has one or more JSON objects, the JSON objects are not separated by a comma. So I need to split them between "}{" and keep both curly braces. This is what the string looks like:

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

I would like a string array like using string.split()

["{id:"123",name:"myName"}", "{"id:"456",name:"anotherName"}"]
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Rebeka
  • 283
  • 1
  • 2
  • 13
  • possible duplicate of http://stackoverflow.com/questions/2773710/php-as3-regex-to-split-multiple-json-in-one – Matti Lyra Nov 14 '12 at 17:58
  • I dont know about that, that question has JSON Objects inside of objects, I am trying to do something much more simple but don't know how. Right now I am using String[] temp = json.split("\\}\\{"); and it gets the first one fine but I think it deletes some of the curly braces so the 2nd object isn't correct. – Rebeka Nov 14 '12 at 18:54
  • If there is any chance, that some string value in the JSON may contain `}{`, then your only chance is to really parse it. You can parse it either as real JSON, or just parse it enough to separate string contents, possibly inlcuding double quotes too, from the rest, but parse it you must. – hyde Nov 14 '12 at 19:23
  • I guess there is a slim possibility that someone could enter comments with }{ in it. (there is a comments field in the JSON object). Right now I am using String[] temp = json.split("(?=\\{)"); and it is working but I didn't think about this issue your brought up. thanks! – Rebeka Nov 14 '12 at 19:47
  • To people voting to close : Please read both questions. The other is about the splitting in PHP of a complex multi-level JSON string (which is barely possible without parsing), while this one is about the splitting in java of a specific one-level JSON string (which is of course doable). – Denys Séguret Nov 23 '12 at 16:18

1 Answers1

15

If your objects aren't more complex than what you show, you may use lookarounds like this :

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

Exemple :

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, a regex wouldn't probably work and you would have to parse your string.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758