0

I have a JSON which has many arrays with a different name, just like below JSON.

{
  "CA": [
    {
      "high": 5,
      "low": 3,
      "key": "ABPS"
    },
    {
      "high": 6,
      "low": 2,
      "key": "ABPO"
    }
  ],
  "EE": [
    {
      "high": 8,
      "low": 4,
      "key": "ABPS"
    },
    {
      "high": 7,
      "low": 2,
      "key": "ABPO"
    }
  ]
}

I am trying to iterate JSON array values dynamically without specifying the name of the array.

I am able to read array with specifying the name of the array with below code but how to read array values dynamically without specifying the name of every array because the JSON file I have it has thousands of array.

package com.abc;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonRead {

    private static final String filePath = "jsonTestFile.json";

    public static void main(String[] args) {

        try (FileReader reader = new FileReader(ClassLoader.getSystemResource(filePath).getFile())) {

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

            // get an array from the JSON object
            JSONArray lang = (JSONArray) jsonObject.get("CA");

            Iterator i = lang.iterator();

            // take each value from the json array separately
            while (i.hasNext()) {
                JSONObject innerObj = (JSONObject) i.next();
                System.out.println("high " + innerObj.get("high") + " low " + innerObj.get("low")+ " key " + innerObj.get("key"));
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
0

1 Answer 1

0

This might help

for (Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
  String key = (String) iterator.next();
  JSONArray jArray = (JSONArray) jsonObject.get(key);
  }
Sign up to request clarification or add additional context in comments.

Comments

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.