How do you parse a nested JSON file like below using Processing JSON object?

Shyamal Chandra :

How do you parse a nested JSON file like below using Processing JSON object? I am trying to figure out how to parse JSON that is multi-level.

{
  "info": {
    "description": "COCO 2014 Dataset",
    "url": "http://cocodataset.org",
    "version": "1.0",
    "year": 2014,
    "contributor": "COCO Consortium",
    "date_created": "2017/09/01"
  },
  "images": [
    {
      "license": 5,
      "file_name": "COCO_train2014_000000057870.jpg",
      "coco_url": "http://images.cocodataset.org/train2014/COCO_train2014_000000057870.jpg",
      "height": 480,
      "width": 640,
      "date_captured": "2013-11-14 16:28:13",
      "flickr_url": "http://farm4.staticflickr.com/3153/2970773875_164f0c0b83_z.jpg",
      "id": 57870
    },
George Profenza :

Have a look at JSONObject and JSONArray to see the available methods bellow on each page, each with documentation and examples.

Regarding your structure, here's a quick snippet on how you might access nested JSON objects and arrays:

// assume data is a JSONObject pointing to the loaded json data (via loadJSONObject / JSONObject.parse(), etc.

// access the info object
JSONObject info = data.getJSONObject("info");
// access the images array object
JSONArray images = data.getJSONArray("images");
// access a string inside an object
println(info.getString("description"));
// access a JSON object inside a JSON array
JSONObject firstImage = images.getJSONObject(0);

// acess an integer
println(firstImage.getInt("id"));
// ... and a string again
println(firstImage.getString("flickr_url"));

If you name your loaded JSONObject variable data, paste the the snippet above and run, it should print:

COCO 2014 Dataset
57870
http://farm4.staticflickr.com/3153/2970773875_164f0c0b83_z.jpg

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328263&siteId=1