Athul Sukumaran
Athul Sukumaran

Reputation: 360

Java: Append key value pair to nested json object

I am given three inputs .

My task is to append the key value pair to a node by looking at the node structure and updating the original JSON.

For example, if the inputs are,

  1. JSON Object

    {
      a:
         {
           b:
              {
                c:{}
              }     
         }
    }
    
  2. Node structure

    a.b.
    
  3. Key k and value v

The final updated JSON should look like

    {
      a:
         {
           b:
              {
                key:val
                c:{}
              }     
         }
    }

Please note that the original JSON can be {} also. Then I have to build the whole JSON by looking at the node structure.

Here is my code

Upvotes: 4

Views: 9239

Answers (1)

Nicolas Filotto
Nicolas Filotto

Reputation: 45005

It could be done using String#split(regex) as next:

public void modifiedJSON(JSONObject orgJson, String nodeStruct, 
                         String targetKey, String value)  {
    // Split the keys using . as separator 
    String[] keys = nodeStruct.split("\\.");
    // Used to navigate in the tree
    // Initialized to the root object
    JSONObject target = orgJson;
    // Iterate over the list of keys from the first to the key before the last one
    for (int i = 0; i < keys.length - 1; i++) {
        String key = keys[i];
        if (!target.has(key)) {
            // The key doesn't exist yet so we create and add it automatically  
            target.put(key, new JSONObject());
        }
        // Get the JSONObject corresponding to the current key and use it
        // as new target object
        target = target.getJSONObject(key);
    }
    // Set the last key
    target.put(targetKey, value);
}

Upvotes: 4

Related Questions