This is a working example based (and tested) with gson-2.8.0. It accepts an arbitrary sequence of JSON objects on a given input stream. And, of course, it does not impose any restrictions on how you have formatted your input:

       InputStream is = /* whatever */
       Reader r = new InputStreamReader(is, "UTF-8");
       Gson gson = new GsonBuilder().create();
       JsonStreamParser p = new JsonStreamParser(r);

       while (p.hasNext()) {
          JsonElement e = p.next();
          if (e.isJsonObject()) {
              Map m = gson.fromJson(e, Map.class);
              /* do something useful with JSON object .. */
          }
          /* handle other JSON data structures */
       }
Answer from wh81752 on Stack Overflow
Top answer
1 of 10
14

This is a working example based (and tested) with gson-2.8.0. It accepts an arbitrary sequence of JSON objects on a given input stream. And, of course, it does not impose any restrictions on how you have formatted your input:

       InputStream is = /* whatever */
       Reader r = new InputStreamReader(is, "UTF-8");
       Gson gson = new GsonBuilder().create();
       JsonStreamParser p = new JsonStreamParser(r);

       while (p.hasNext()) {
          JsonElement e = p.next();
          if (e.isJsonObject()) {
              Map m = gson.fromJson(e, Map.class);
              /* do something useful with JSON object .. */
          }
          /* handle other JSON data structures */
       }
2 of 10
10

I know it has been almost one year for this post :) but i am actually reposing again as an answer because i had this problem same as you Yuan

I have this text.txt file - I know this is not a valid Json array - but if you look, you will see that each line of this file is a Json object in its case alone.

{"Sensor_ID":"874233","Date":"Apr 29,2016 08:49:58 Info Log1"}
{"Sensor_ID":"34234","Date":"Apr 29,2016 08:49:58 Info Log12"}
{"Sensor_ID":"56785","Date":"Apr 29,2016 08:49:58 Info Log13"}
{"Sensor_ID":"235657","Date":"Apr 29,2016 08:49:58 Info Log14"}
{"Sensor_ID":"568678","Date":"Apr 29,2016 08:49:58 Info Log15"}

Now I want to read each line of the above and parse the names "Sensor_ID" and "Date" into Json format. After long search, I have the following:

Try it and look on the console to see the result. I hope it helps.

package reading_file;

import java.io.*;
import java.util.ArrayList;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class file_read {
public static void main(String [] args) {
    ArrayList<JSONObject> json=new ArrayList<JSONObject>();
    JSONObject obj;
    // The name of the file to open.
    String fileName = "C:\\Users\\aawad\\workspace\\kura_juno\\data_logger\\log\\Apr_28_2016\\test.txt ";

    // This will reference one line at a time
    String line = null;

    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = new FileReader(fileName);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null) {
            obj = (JSONObject) new JSONParser().parse(line);
            json.add(obj);
            System.out.println((String)obj.get("Sensor_ID")+":"+
                               (String)obj.get("Date"));
        }
        // Always close files.
        bufferedReader.close();         
    }
    catch(FileNotFoundException ex) {
        System.out.println("Unable to open file '" + fileName + "'");                
    }
    catch(IOException ex) {
        System.out.println("Error reading file '" + fileName + "'");                  
        // Or we could just do this: 
        // ex.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}
Discussions

How to read JSON with multiple objects java - Stack Overflow
There should be a different get method for getting an array stleary.github.io/JSON-java/org/json/… More on stackoverflow.com
🌐 stackoverflow.com
October 19, 2018
In Java, How do I represent multiple objects (of same type) in a single JSON object
I need to pass the attribtutes of particular type, as apart of a restful service to a javascript which will then display them to a webpage @GET @Produces("application/json") @Consumes(" More on stackoverflow.com
🌐 stackoverflow.com
java - How to Parse a JSON object with contains multiple JSON objects ( not an array) of the same type - Stack Overflow
I have a JSON Object with multiple JSON objects within it, all of the same type. More on stackoverflow.com
🌐 stackoverflow.com
java - How to create multiple JSON objects via for loop - Stack Overflow
I need to create variable amount of JSON objects and JSON arrays based on the result set from a database query. The JSON format looks very similar to the following which is used for a google chart.... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
Top answer
1 of 3
2

Your json fragment is invalid - the last comma breaks the parsing. But the rest of the code is quite workable.

    String res = "[\n" +
            "    {\n" +
            "        \"Class\": \"1\",\n" +
            "        \"school\": \"test\",\n" +
            "        \"description\": \"test\",\n" +
            "        \"student\": [\n" +
            "            \"Student1\",\n" +
            "            \"Student2\"\n" +
            "        ],\n" +
            "        \"qualify\": true,\n" +
            "        \"annualFee\": 3.00\n" +
            "       }\n" +
            "]";

    JSONArray arr = new JSONArray(res);
    for (int i = 0; i < arr.length(); i++) {
        JSONObject block = arr.getJSONObject(i);
        Integer cls = block.getInt("Class");
        System.out.println("cls = " + cls);
        Object school = block.getString("school");
        System.out.println("school = " + school);
        JSONArray students = block.getJSONArray("student");
        System.out.println("student[0] = " + students.get(0));
        System.out.println("student[1] = " + students.get(1));
    }

should output

cls = 1
school = test
student[0] = Student1
student[1] = Student2
2 of 3
1

Your JSON reponse root is array but you consider your JSON response as JSON object

Changing your parsing json code as below

String res=cspResponse.prettyPrint();
    org.json.JSONArray arr = new org.json.JSONArray(res);
    String dataStatus=null;
    for (int i = 0; i < arr.length(); i++) {
        org.json.JSONObject obj=arr.getJSONObject(i);
        dataStatus = obj.getString(key);
        System.out.println("dataStatus is \t" + dataStatus);
        String schoolName = org.getString("school");
        System.out.println("school => " + schoolName);
        org.json.JSONArray students = obj.getJSONArray("student");
        System.out.println("student[0] = " + students.get(0));
        System.out.println("student[1] = " + students.get(1));
    }
🌐
CodeProject
codeproject.com › Questions › 1164374 › How-to-add-multiple-object-in-JSON-object-array
How to add multiple object in JSON object/array?
Do not try and find the page. That’s impossible. Instead only try to realise the truth - For those who code; Updated: 1 Jul 2007
🌐
Stack Overflow
stackoverflow.com › questions › 52884531 › how-to-read-json-with-multiple-objects-java
How to read JSON with multiple objects java - Stack Overflow
October 19, 2018 - CopyString result = getJsonResponse(); try { JSONArray jsonResponse = new JSONArray(result); // Step through each of the Items returned for (int i = 0; i <jsonResponse.length(); i++) { JSONObject jsonItem = jsonResponse.getJSONObject(i); Item item = new Item(); item .setIndex(jsonItem.getInt("Index")); item .setName(jsonItem.getString("Name")); item .setActive(jsonItem.getBoolean("Active")); item .setExists(jsonItem.getBoolean("Exists")); item .setShouldExecuteSchedule(jsonItem.getBoolean("Execute")); hardware.getItems().add(item); } } catch (JSONException e) { e.printStackTrace(); passed = fa
Find elsewhere
🌐
YouTube
youtube.com › watch
JSON Basics JSON multiple objects within JSON files - YouTube
JSON Course covers everything from start to finish to get you using JSON quickly!•Learn the basics of JSON •JSON structure data of delivery•basics of JavaScr...
Published: March 25, 2016
Top answer
1 of 3
1

Have you should try to use a framework like jackson Who will let unmarshall your json to real java object of your choice for example :

public class Data
{
   private String blukiiId;
   private String macAddress;
   private String type;
   ...
   private List<RSSI> rssi;
   private BeaconSensorData beaconSensorData;
}

With Rssi,BeaconSensorData another class like that etc... Now your code will get Converted as below

public class getJSON
{
   
   public static void main(String[] args) throws Exception{
       ObjectMapper mapper = new ObjectMapper();
       // Set any extra configs like ignore fields etc here

       try{
            Data data = mapper.convertValue(Files.readAllBytes(Paths.get("test.json"), Data.class);

            //Now you can access the value as below
            data.getBeaconSensorData().getEnvironment().getTemperature();
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
}


2 of 3
0

If you can only use org.json.simple.parser.JSONParser, please refer to the following java code by recursion.

import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class getJSON
{
    private static void visitElement(Object obj, Map<Object, Object> map) throws Exception {
        if(obj instanceof JSONArray) {
            JSONArray jsonArr = (JSONArray)obj;
            Iterator<?> itr = jsonArr.iterator();
            while(itr.hasNext())
                visitElement(itr.next(), map);
        }
        else if(obj instanceof JSONObject) {
            JSONObject jsonObj = (JSONObject)obj;
            Iterator<?> itr = jsonObj.keySet().iterator();
            while(itr.hasNext()) {
                Object key = itr.next();
                Object value = jsonObj.get(key);
                map.put(key, value);
                visitElement(value, map);                 
            }
        }
    }
   
   public static void main(String[] args) throws Exception{
       JSONParser parser = new JSONParser();
       
       try{
           Object obj = parser.parse(new FileReader("C:/test.json"));
           Map<Object, Object> map = new HashMap<>();
           visitElement(obj, map);
           for(Object key : map.keySet())
               System.out.println(key + ": " + map.get(key));
           
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
}
Top answer
1 of 16
66

If you want a new object with two keys, Object1 and Object2, you can do:

JSONObject Obj1 = (JSONObject) jso1.get("Object1");
JSONObject Obj2 = (JSONObject) jso2.get("Object2");
JSONObject combined = new JSONObject();
combined.put("Object1", Obj1);
combined.put("Object2", Obj2);

If you want to merge them, so e.g. a top level object has 5 keys (Stringkey1, ArrayKey, StringKey2, StringKey3, StringKey4), I think you have to do that manually:

JSONObject merged = new JSONObject(Obj1, JSONObject.getNames(Obj1));
for(String key : JSONObject.getNames(Obj2))
{
  merged.put(key, Obj2.get(key));
}

This would be a lot easier if JSONObject implemented Map, and supported putAll.

2 of 16
32

In some cases you need a deep merge, i.e., merge the contents of fields with identical names (just like when copying folders in Windows). This function may be helpful:

/**
 * Merge "source" into "target". If fields have equal name, merge them recursively.
 * @return the merged object (target).
 */
public static JSONObject deepMerge(JSONObject source, JSONObject target) throws JSONException {
    for (String key: JSONObject.getNames(source)) {
            Object value = source.get(key);
            if (!target.has(key)) {
                // new value for "key":
                target.put(key, value);
            } else {
                // existing value for "key" - recursively deep merge:
                if (value instanceof JSONObject) {
                    JSONObject valueJson = (JSONObject)value;
                    deepMerge(valueJson, target.getJSONObject(key));
                } else {
                    target.put(key, value);
                }
            }
    }
    return target;
}



/**
 * demo program
 */
public static void main(String[] args) throws JSONException {
    JSONObject a = new JSONObject("{offer: {issue1: value1}, accept: true}");
    JSONObject b = new JSONObject("{offer: {issue2: value2}, reject: false}");
    System.out.println(a+ " + " + b+" = "+JsonUtils.deepMerge(a,b));
    // prints:
    // {"accept":true,"offer":{"issue1":"value1"}} + {"reject":false,"offer":{"issue2":"value2"}} = {"reject":false,"accept":true,"offer":{"issue1":"value1","issue2":"value2"}}
}
🌐
Stack Overflow
stackoverflow.com › questions › 5656123 › json-string-parsing-to-java-object-with-multiple-objects
Json string parsing to java object with multiple objects - Stack Overflow
November 7, 2011 - Trying to parse the following json string to java object using gson { "entry": "132456", "product": { "item": "123456", "prompts": [ { "promptId...
Top answer
1 of 2
2

I think the json string you provided should be like

"{\"bills\":[{\"amount\":\"13\",\"billId\":\"billid3\"} ,{\"amount\":\"155\",\"billId\":\"billid4\"}]}"

If this is the case, you can use the solution below:

Create two classes Bill.java and TestObject.java as follows:

Bill.java

public class Bill {
    private double amount;
    private String billId;
    /**
     * @return the amount
     */
    public double getAmount() {
        return amount;
    }
    /**
     * @param amount the amount to set
     */
    public void setAmount(double amount) {
        this.amount = amount;
    }
    /**
     * @return the billId
     */
    public String getBillId() {
        return billId;
    }
    /**
     * @param billId the billId to set
     */
    public void setBillId(String billId) {
        this.billId = billId;
    }

}

TestObject.java

import java.util.List;

public class TestObject {

    private List<Bill> bills;

    /**
     * @return the bills
     */
    public List<Bill> getBills() {
        return bills;
    }

    /**
     * @param bills the bills to set
     */
    public void setBills(List<Bill> bills) {
        this.bills = bills;
    }

}

Here is the main program to test the code.

Test.java

import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

    public static void main(String[] args) {
        String jsonStr = "{\"bills\":[{\"amount\":\"13\",\"billId\":\"billid3\"} ,{\"amount\":\"155\",\"billId\":\"billid4\"}]}";

        ObjectMapper mapper = new ObjectMapper();
        try {
            TestObject testObject = mapper.readValue(jsonStr, TestObject.class);
            System.out.print(testObject);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}
2 of 2
1

I have used gson-2.2.2.jar.

Please find code given below :

Bill.java

public class Bill
{
    private double  billAmount;

    private String  billId;

    //getters and setters
}

Main.java

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Main
{
    public static void main(String[] args)
    {
        Bill bill = null;
        List<Bill> bills = new ArrayList<Bill>();
        for (int i = 0; i < 5; i++)
        {
            bill = new Bill();
            bill.setBillAmount(100 + (i + 1));
            bill.setBillId("bill_id_" + (i + 1));
            bills.add(bill);
        }
        Gson gson = new Gson();
        String json = gson.toJson(bills, new TypeToken<List<Bill>>()
        {}.getType());
        System.out.println(json);

        Type mapType = new TypeToken<List<Bill>>()
        {}.getType();
        List<Bill> billsRetrieved = new Gson().fromJson(json, mapType);
        for (Bill bill2 : billsRetrieved)
        {
            System.out.println(bill2.getBillId());
        }
    }
}

OutPut :

[
   {
      "billAmount":101.0,
      "billId":"bill_id_1"
   },
   {
      "billAmount":102.0,
      "billId":"bill_id_2"
   },
   {
      "billAmount":103.0,
      "billId":"bill_id_3"
   },
   {
      "billAmount":104.0,
      "billId":"bill_id_4"
   },
   {
      "billAmount":105.0,
      "billId":"bill_id_5"
   }
]

bill_id_1 bill_id_2 bill_id_3 bill_id_4 bill_id_5

Please revert in case you need further explanation.

Top answer
1 of 6
188

On the outermost level, a JSON object starts with a { and end with a }.

Sample data:

{
    "cars": {
        "Nissan": [
            {"model":"Sentra", "doors":4},
            {"model":"Maxima", "doors":4},
            {"model":"Skyline", "doors":2}
        ],
        "Ford": [
            {"model":"Taurus", "doors":4},
            {"model":"Escort", "doors":4}
        ]
    }
}

If the JSON is assigned to a variable called data, then accessing it would be like the following:

data.cars['Nissan'][0].model   // Sentra
data.cars['Nissan'][1].model   // Maxima
data.cars['Nissan'][2].doors   // 2

for (var make in data.cars) {
    for (var i = 0; i < data.cars[make].length; i++) {
        var model = data.cars[make][i].model;
        var doors = data.cars[make][i].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Another approach (using an associative array for car models rather than an indexed array):

{
    "cars": {
        "Nissan": {
            "Sentra": {"doors":4, "transmission":"automatic"},
            "Maxima": {"doors":4, "transmission":"automatic"}
        },
        "Ford": {
            "Taurus": {"doors":4, "transmission":"automatic"},
            "Escort": {"doors":4, "transmission":"automatic"}
        }
    }
}

data.cars['Nissan']['Sentra'].doors   // 4
data.cars['Nissan']['Maxima'].doors   // 4
data.cars['Nissan']['Maxima'].transmission   // automatic

for (var make in data.cars) {
    for (var model in data.cars[make]) {
        var doors = data.cars[make][model].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Edit:

Correction: A JSON object starts with { and ends with }, but it's also valid to have a JSON array (on the outermost level), that starts with [ and ends with ].

Also, significant syntax errors in the original JSON data have been corrected: All key names in a JSON object must be in double quotes, and all string values in a JSON object or a JSON array must be in double quotes as well.

See:

  • JSON specification
  • JSONLint - The JSON validator
2 of 6
23

A good book I'm reading: Professional JavaScript for Web Developers by Nicholas C. Zakas 3rd Edition has the following information regarding JSON Syntax:

"JSON Syntax allows the representation of three types of values".

Regarding the one you're interested in, Arrays it says:

"Arrays are represented in JSON using array literal notation from JavaScript. For example, this is an array in JavaScript:

var values = [25, "hi", true];

You can represent this same array in JSON using a similar syntax:

[25, "hi", true]

Note the absence of a variable or a semicolon. Arrays and objects can be used together to represent more complex collections of data, such as:

{
    "books":
              [
                {
                    "title": "Professional JavaScript",
                    "authors": [
                        "Nicholas C. Zakas"
                    ],
                    "edition": 3,
                    "year": 2011
                },
                {
                    "title": "Professional JavaScript",
                    "authors": [
                        "Nicholas C.Zakas"
                    ],
                    "edition": 2,
                    "year": 2009
                },
                {
                    "title": "Professional Ajax",
                    "authors": [
                        "Nicholas C. Zakas",
                        "Jeremy McPeak",
                        "Joe Fawcett"
                    ],
                    "edition": 2,
                    "year": 2008
                }
              ]
}

This Array contains a number of objects representing books, Each object has several keys, one of which is "authors", which is another array. Objects and arrays are typically top-level parts of a JSON data structure (even though this is not required) and can be used to create a large number of data structures."

To serialize (convert) a JavaScript object into a JSON string you can use the JSON object stringify() method. For the example from Mark Linus answer:

var cars = [{
    color: 'gray',
    model: '1',
    nOfDoors: 4
    },
    {
    color: 'yellow',
    model: '2',
    nOfDoors: 4
}];

cars is now a JavaScript object. To convert it into a JSON object you could do:

var jsonCars = JSON.stringify(cars);

Which yields:

"[{"color":"gray","model":"1","nOfDoors":4},{"color":"yellow","model":"2","nOfDoors":4}]"

To do the opposite, convert a JSON object into a JavaScript object (this is called parsing), you would use the parse() method. Search for those terms if you need more information... or get the book, it has many examples.

🌐
Stack Overflow
stackoverflow.com › questions › 31079592 › access-multiple-json-objects-in-java
Access multiple json objects in java - Stack Overflow
I encountered array parsing problems (missing/null elements) using the JSON.org Java parser. A better alternative is the Jackson JSON Processor. ... Save this answer. ... Show activity on this post. ... public void JsontoString() { String jsonString = "{\"root\":[{\"title\":\"Event 1\"," + "\"param\":[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\"]," + "\"status\":true," + "\"values\":[{" + "\"0\":{\"0\":\"1_a\",\"1\":\"1_b\"}," + "\"1\":{\"0\":\"2_a\",\"1\":\"2_b\"}}]" + ",\"$$hashKey\":\"object:3\"}" + ",{\"title\":\"Event 2\"," + "\"param\":[\"1\",\"2\",\"3\",\"4\",\"Price1\",\"Price2\",\"5\",\"
Top answer
1 of 1
2
String.valueOf(gameService.convertLikesToJsonArray(averageLikesPerGame)); 

You are making this a single value in the json, instead of it being actual json. That's why it's all escaped in your JSON output. You also haven't shown your pretty print method, so can't comment on the output of that. Try

    //Use object instead of String as you want nested objects in output
    Map<String, Object> report = new HashMap<>();

    String highestRankedGame = gameService.findHighestRatedGame();
    String userWithMostComments = gameService.findUserWithMostComments();
    Map<String,String> averageLikesPerGame = gameService.findAverageLikesPerGame();

    report.put("highest_rated_game",highestRankedGame);
    report.put("user_with_most_comments", userWithMostComments);
   //Add averageLikesPerGame directly to report without modifying
    report.put("average_likes_per_game",averageLikesPerGame.entrySet());

    String jsonReport = gameService.convertReportToJson(report);

    return jsonReport;

And

public String convertReportToJson(Map<String, Object> report) {

    ObjectMapper mapper = new ObjectMapper();
    String jsonArray = null;
    try {
        //Don't need Gson, can use writerWithDefaultPrettyPrinter with Jackson which 
        //You are already using
        jsonArray = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(report);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return jsonArray;
}

If you want mapped values in the array with labels then you could do something like this

    List<Map<String,String>> labelledAvgLikesPerGame =
            averageLikesPerGame.entrySet().stream()
                    .map( entry ->
                           //Needs java 9+ for ofEntries
                           //You'll need to make new HashMap,put + return
                           // for java 8
                            Map.ofEntries(
                                    Map.entry("title", entry.getKey()),
                                    Map.entry("average_likes", entry.getValue())
                            )).collect(Collectors.toList());

    report.put("highest_rated_game",highestRankedGame);
    report.put("user_with_most_comments", userWithMostComments);
    report.put("average_likes_per_game",labelledAvgLikesPerGame);
Top answer
1 of 2
2

Use this code and Enjoy :)

private void createJsonStructure() {

    try
    {
        JSONObject rootObject = new JSONObject();

        JSONArray carArr = new JSONArray();
        for (int i = 0; i < 2 ; i++)
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("CarId", "123");
            jsonObject.put("Status", "Ok");
            carArr.put(jsonObject);
        }
        rootObject.put("Car", carArr);


        JSONArray motorArr = new JSONArray();
        for (int i = 0; i < 2 ; i++)
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MotorId", "123");
            jsonObject.put("Status", "Ok");
            motorArr.put(jsonObject);
        }
        rootObject.put("Motor", motorArr);


        JSONArray busArr = new JSONArray();
        for (int i = 0; i < 2 ; i++)
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("BusId", "123");
            jsonObject.put("Status", "Ok");
            busArr.put(jsonObject);
        }
        rootObject.put("Bus", busArr);

        Log.e("JsonObject", rootObject.toString(4));

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
2 of 2
1
    JSONObject motorObject = new JSONObject();
    JSONObject busObject = new JSONObject();
    JSONObject carObject = new JSONObject();
    JSONObject wholeObject =new JSONObject();

    JSONArray motorArray = new JSONArray();
    JSONArray busArray = new JSONArray();
    JSONArray carArray = new JSONArray();

    motorArray.put(motorTracks.getJSONObject());
    busArray.put(buss.getJSONObject());
    carArray.put(car.getJSONObject());

    try
    {
        wholeObject.put("Motor",motorArray);
        wholeObject.put("Bus",busArray);
        wholeObject.put("Car",carArray);
        System.out.println(wholeObject);
    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }
🌐
Quora
quora.com › Can-JSON-contain-multiple-objects
Can JSON contain multiple objects? - Quora
Answer (1 of 2): The file is invalid if it contains more than one JSON object. When you try to load and parse a JSON file with multiple JSON objects, each line contains valid JSON, but as a whole, it is not a valid JSON as there is no top-level list or object definition. We can call JSON a valid ...