title: Java: Append key value pair to nested json object
body: <p>I am given three inputs .</p>
  
  <ul>
  <li><p>A JSON object (nested)</p></li>
  <li><p>A node structure</p></li>
  <li>key value pair</li>
  </ul>
  
  <p>My task is to append the key value pair to a node by looking at the node structure and updating the original JSON.</p>
  
  <blockquote>
    <p>For example, if the inputs are,</p>
  </blockquote>
  
  <ol>
  <li><p>JSON Object </p>
  
  <pre><code>{
    a:
       {
         b:
            {
              c:{}
            }     
       }
  }
  </code></pre></li>
  <li><p>Node structure</p>
  
  <pre><code>a.b.
  </code></pre></li>
  <li><p>Key <code>k</code> and value <code>v</code></p></li>
  </ol>
  
  <p>The final updated JSON should look like</p>
  
  <pre><code>    {
        a:
           {
             b:
                {
                  key:val
                  c:{}
                }     
           }
      }
  </code></pre>
  
  <blockquote>
    <p>Please note that the original JSON can be <code>{}</code> also. Then I have to build the whole JSON by looking at the node structure.</p>
  </blockquote>
  
  <p>Here is my code</p>
  
  <ul>
  <li><p>making a key value pair</p>
  
  <pre><code> public JSONObject makeEV(String ele, String val) throws JSONException{      
     JSONObject json =new JSONObject();
     json.put(ele, val);
     return json;
   }
  </code></pre></li>
  <li><p>Appending it to JSON</p>
  
  <pre><code>public void modifiedJSON(JSONObject orgJson, String nodeStruct, JSONObject ev) throws JSONException{
  JSONObject newJson = new JSONObject();
  JSONObject copyJson = newJson;
  
  char last = nodeStruct.charAt(nodeStruct.length()-1);
  String lastNode = String.valueOf(last);
  
  int i = 0; 
  while(orgJson.length() != 0 || i&lt; nodeStruct.length()){
  
      if(orgJson.length() ==0){
          if(nodeStruct.charAt(i) == last){
              newJson.put(String.valueOf(last), ev.toString());
          }else{
              newJson.put(String.valueOf(nodeStruct.charAt(i)), "");
          }
          newJson = newJson.getJSONObject(String.valueOf(nodeStruct.charAt(i)));
  
      }
      else if(i &gt;= nodeStruct.length()){
          if(orgJson.has(lastNode)){
              newJson.put(String.valueOf(last), ev.toString());
          }else{
  
          }
      }
  }
  }
  </code></pre>
  
  <p>I am stuck here. Please help. Thanks in advance.</p></li>
  </ul>