Core Java

JSONObject Extract Keys Example

Working with JSON in Java is common when dealing with APIs, configurations, or data pipelines. One common task is extracting all keys from a JSON object, especially when the structure can be nested. Let us delve into understanding how to use Java’s JSONObject to extract keys from JSON data.

1. What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and easy to parse and generate for machines. It is commonly used to transmit data between a server and a web application.

A flat JSON structure consists of simple key-value pairs where each key maps directly to a value, such as a string, number, or boolean—for example: {"name": "Alice", "age": 30}.

On the other hand, a nested JSON includes values that are themselves JSON objects or arrays, allowing for a more hierarchical structure. For example, {"name": "Alice", "address": {"city": "New York", "zipcode": "10001"}} contains a nested object under the key address. In such cases, keys can be accessed using dot notation (like address.city) or bracket notation for array elements (like phones[0]).

Understanding both flat and nested keys is essential when parsing or transforming JSON data in applications.

2. Code Example: Extracting Keys from Flat and Nested JSON

Let’s take a combined approach by using a single JSON string that includes both flat and nested structures. We’ll build a recursive method that walks through all key paths and prints them in dot and bracket notation for clarity.

// JSONKeyExtractor.java

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JSONKeyExtractor {
    public static void main(String[] args) {
        String jsonStr = """
        {
            "name": "Alice",
            "age": 25,
            "city": "New York",
            "address": {
                "street": "123 Main St",
                "zipcode": "10001",
                "coordinates": {
                    "lat": 40.7128,
                    "lon": -74.0060
                }
            },
            "phones": ["123-4567", "890-1234"],
            "projects": [
                {
                    "name": "Project X",
                    "status": "active"
                },
                {
                    "name": "Project Y",
                    "status": "completed"
                }
            ]
        }
        """;

        JSONObject jsonObject = new JSONObject(jsonStr);
        List<String> allKeys = new ArrayList<>();
        extractKeys(jsonObject, "", allKeys);

        for (String key : allKeys) {
            System.out.println("Key: " + key);
        }
    }

    private static void extractKeys(JSONObject obj, String prefix, List<String> keys) {
        Iterator<String> itr = obj.keys();
        while (itr.hasNext()) {
            String key = itr.next();
            Object value = obj.get(key);
            String fullKey = prefix.isEmpty() ? key : prefix + "." + key;

            keys.add(fullKey);

            if (value instanceof JSONObject) {
                extractKeys((JSONObject) value, fullKey, keys);
            } else if (value instanceof JSONArray) {
                JSONArray array = (JSONArray) value;
                for (int i = 0; i < array.length(); i++) {
                    Object element = array.get(i);
                    if (element instanceof JSONObject) {
                        extractKeys((JSONObject) element, fullKey + "[" + i + "]", keys);
                    } else {
                        keys.add(fullKey + "[" + i + "]");
                    }
                }
            }
        }
    }
}

2.1 Code Explanation

The given Java code defines a class JSONKeyExtractor which demonstrates how to recursively extract all flat and nested keys from a complex JSON object using the org.json library. It begins by declaring a multiline JSON string containing various data types like primitive values (name, age), nested objects (address, coordinates), arrays of strings (phones), and arrays of objects (projects). The main method parses this string into a JSONObject and initializes an empty list to store the extracted keys. The method extractKeys is then called, which recursively navigates through the JSON structure. If a key’s value is another JSONObject, it recurses with an updated prefix to build the full key path (like address.street or address.coordinates.lat). If the value is a JSONArray, it iterates through each element: if the element is a JSONObject, it recurses again with the index included in the path (e.g., projects[0].name), otherwise, it adds the indexed key directly (e.g., phones[1]). After the extraction, all the keys collected are printed to the console, showcasing both flat and deeply nested keys in a readable dot and bracket notation that reflects their hierarchy in the original JSON.

2.2 Code Output

When you run the code, it prints out all the keys from the JSON, including both top-level and nested ones, using dot and bracket notation to show their structure.

Key: name
Key: age
Key: city
Key: address
Key: address.street
Key: address.zipcode
Key: address.coordinates
Key: address.coordinates.lat
Key: address.coordinates.lon
Key: phones
Key: phones[0]
Key: phones[1]
Key: projects
Key: projects[0].name
Key: projects[0].status
Key: projects[1].name
Key: projects[1].status

3. Best Practices

  • Use dot and bracket notation for nested keys — this approach helps maintain clear and consistent access paths, especially when working with deeply nested JSON structures.
  • Recursively handle JSONObjects and JSONArrays to ensure keys are extracted at all levels of the JSON. This is essential for handling complex and unpredictable data formats.
  • Avoid assumptions about array contents — always check the type of each element in the array before accessing or casting, as JSON arrays can contain mixed types.
  • Consider using a JSON schema if working with expected formats repeatedly. This can help validate and enforce the structure of your JSON, reducing the chances of runtime errors.
  • Validate the JSON structure before extracting keys, especially when dealing with user-generated or third-party data. This ensures robustness and prevents issues caused by malformed or unexpected input.

4. Conclusion

Extracting keys from JSON data in Java requires thoughtful handling of both flat and nested structures. By using recursion and type checks, you can easily walk through the JSON tree and collect all key paths in a readable format. This can be especially useful for tasks like auditing API responses, transforming data, or building dynamic form UIs. For more advanced use cases, libraries like Jackson or Gson offer more control and flexibility, but org.json remains a simple and effective choice for lightweight use cases.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button