Search code examples
javajsonjson-simple

Simple JSON unexpected token { at position > 1


I'm trying to use JSON simple as part of a Java application to pull specific data from a .json file. Whenever I run the program, I get an unexpected token error message when it tries to parse.

A simplified version of the JSON file is as follows:

{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"}
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}

My code is as follows:

public static void readJSON() {

    JSONParser jsonParser = new JSONParser();
    try {

        FileReader reader = new FileReader(fileLocation);
        JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
        JSONArray jsonArray = (JSONArray) jsonObject.get("");

        Iterator<?> i = jsonArray.iterator();

        while (i.hasNext()) {
            JSONObject obj = (JSONObject) i.next();
            int tweetID = (int) obj.get("id");
            String lang = (String) obj.get("lang");         
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
} 

In this example, the line of code:

JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

throws an error due to an unexpected token at the first left brace ({) of the second JSON object (i.e, at the brace before "id":345).

How could I go about resolving this issue? And, as a follow up, how would one also pull the information for the username in this example?

Thanks for taking the time to read through this, and for any assistance provided!


Solution

  • That file is an invalid JSON file, it contains an entire object on each line.

    What you'll need to do is read the file line by line, and then passing each line to the parser to create a new object.