0

i'm using a java function to extract a json file from URL and then applying a web scraping to get data. the link of json data : https://covid.ourworldindata.org/data/owid-covid-data.json

 public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = rd.readLine();
        System.out.println(jsonText.toString());
        JSONObject json = new JSONObject(jsonText);

        return json;

    } finally { is.close(); }
}

and the function to extract data :

 public void setHistoriqueData() throws Exception {
    JSONObject json = readJsonFromUrl("https://covid.ourworldindata.org/data/owid-covid-data.json");
    JSONArray jsonArray = new JSONArray(json.getJSONArray("AFG").toString());
    int length = jsonArray.length() ;
    String key = null;
    String value = null;
    for (int i = 0; i <= length; i++) {
        Set<String> keys = json.getJSONArray("AFG").getJSONObject(i).keySet();
        Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            key = it.next();
            value = json.getJSONArray("AFG").getJSONObject(i).get(key).toString();
            map.put(key, value);
            System.out.println(map.toString());
        }

i have a classic error Exception in thread "main" org.json.JSONException: A JSONObject text must end with '}' at 1 [character 2 line 1] but as we see the file is well structured.

1 Answer 1

1

The JSON data you read includes linebreaks (absolutely legal), but since you read just one line in String jsonText = rd.readLine(); and immedately parse it, this line does not contain a complete JSON object and the execption is thrown.

Sign up to request clarification or add additional context in comments.

2 Comments

And what you suggest ?
Read the whole file before parsing anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.