Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a simple JSON structure using a regular expression

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"}"]
like image 709
Rebeka Avatar asked Nov 14 '12 17:11

Rebeka


People also ask

Can we use regex in split a string?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.

Can you use regex in JSON?

The JSONata type system is based on the JSON type system, with the addition of the function type. In order to accommodate the regex as a standalone expression, the syntax /regex/ evaluates to a function. Think of the /regex/ syntax as a higher-order function that results in a 'matching function' when evaluated.

Can we split JSON file?

Using BigTextFileSplitter, you can split large JSON file in Windows easily and fast, just a few mouse clicks!

How is data separated in JSON?

JSON has the following syntax. Objects are enclosed in braces ( {} ), their name-value pairs are separated by a comma ( , ), and the name and value in a pair are separated by a colon ( : ). Names in an object are strings, whereas values may be of any of the seven value types, including another object or an array.


1 Answers

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.

like image 145
Denys Séguret Avatar answered Sep 16 '22 13:09

Denys Séguret