How do I extract the "extract" attribute from JSON?

14,777

The structure of the JSON you're trying to parse is this:

{
  "batchcomplete": "",
  "query": {
    "normalized": [
      {
        "from": "Russell's_paradox",
        "to": "Russell's paradox"
      }
    ],
    "pages": {
      "46095": {
        "pageid": 46095,
        "ns": 0,
        "title": "Russell's paradox",
        "extract": "..."
      }

That is, pages inside query is an object, not an array. And then, extract is within another nested object, with key 46095. You can get to the extract field like this:

JSONObject pages = data.getJSONObject("query").getJSONObject("pages");
for (String key : pages.keySet()) {
    String def = pages.getJSONObject(key).getString("extract");
    System.out.println(def);
}
Share:
14,777
Kaushik
Author by

Kaushik

Updated on June 14, 2022

Comments

  • Kaushik
    Kaushik almost 2 years

    I am trying read JSON data from this link.

    I am able to read the entire data inside pages attribute using :

    JSONObject data=(JSONObject)new JSONTokener(IOUtils.toString(new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Russell%27s_paradox"))).nextValue();
    String pageName=data.getJSONObject("query").getString("pages");
    System.out.println(pageName);
    

    I want to get the data from "extract" attribute next from the above mentioned link, which I am unable to. I am new with this and I can't find any resources to learn this.

    I tried the following code but I am getting a JSONException.

    JSONArray arr=data.getJSONArray("pages");
    for(int i=0;i<arr.length();i++){
    String def=arr.getJSONObject(i).getString("extract");
    System.out.println(def);
    }
    

    Help.

  • Kaushik
    Kaushik over 7 years
    Thanks for your comment. But I'm getting a The method keySet() is undefined for the type JSONObject error.
  • janos
    janos over 7 years
    @KaushikS perhaps you're using an older version. Can you upgrade to 20160810 ? If not let me know, and the version you're using.
  • Kaushik
    Kaushik over 7 years
    Thanks brother. Worked perfectly. If it's okay to ask here, can you post some links where I can learn this JSON Parsing with Java, if you can ? @janos
  • janos
    janos over 7 years
    I don't really know... It seems to me you were stuck mainly due to your lack of understanding of JSON and (implied) JavaScript. I would recommend the book "JavaScript the good parts". For Java I would recommend "Effective Java", but it's not specific to parsing, it's about Java "mastery". So these suggestions are admittedly very broad, but this is the only suggestion I can think of that makes sense in the long run.
  • Kaushik
    Kaushik over 7 years
    Yes, I am new to JSON and I'm looking for resources to learn. Thanks for your suggestions.