How to parse a JSON File without root element using org.json.simple?

2.9k Views Asked by At

I want to parse json file "c:/employeesRecord.json" using org.json.simple library. Below is sample json data, each record is sperated by next line in the file.

{"Employees ":["A ;B ;C ;D ;E ;F"],"JobTitle":"Software Engineer"}
{"Employees ":["A ;B ;C ;D ;E ;F"],"JobTitle":"Software Engineer"}
{"Employees ":["A ;B ;C ;D ;E ;F"],"JobTitle":"Software Engineer"}
...

How to parse such json file without root element using org.json.simple.

3

There are 3 best solutions below

0
On

Parse it line by line after spliting by \n.

String[] lines = json.split("\n");
List<JsonObject> objects = new ArrayList<>(lines.length); // depending on the JSON library you are using

for(String line : lines) {
    objects.add(parseJson(line));
}
0
On

Since the full file is not a valid JSON object you will need to parse it line-by-line, ie. read first line, parse it using your parser, save the result and then repeat for the next line.

0
On

You can "tweak" the input from the file and change it into a valid json format

String json = <your json from file>
json = "[" + json + "]";
json = json.replace("\n",",");
// parse your json, now it should be a valid.