You don't need to remove before calling put. JSONObject#put will replace any existing value. Simply call

js.getJSONObject("glossary").getJSONObject("GlossDiv").put("seeds", "555");

But how to get to wanted key for one step?

You don't. You have a nested object tree. You must go through the full tree to reach your element. There might be a library out there that does this for you, but underneath it all, it will be traversing everything.

Answer from Sotirios Delimanolis on Stack Overflow
Top answer
1 of 4
10

You don't need to remove before calling put. JSONObject#put will replace any existing value. Simply call

js.getJSONObject("glossary").getJSONObject("GlossDiv").put("seeds", "555");

But how to get to wanted key for one step?

You don't. You have a nested object tree. You must go through the full tree to reach your element. There might be a library out there that does this for you, but underneath it all, it will be traversing everything.

2 of 4
1

I found solution.

    public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
    String[] keyMain = keys.split("\\.");
    for (String keym : keyMain) {
        Iterator iterator = js1.keys();
        String key = null;
        while (iterator.hasNext()) {
            key = (String) iterator.next();
            if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
                if ((key.equals(keym))) {
                    js1.put(key, valueNew);
                    return js1;
                }
            }
            if (js1.optJSONObject(key) != null) {
                if ((key.equals(keym))) {
                    js1 = js1.getJSONObject(key);
                    break;
                }
            }
            if (js1.optJSONArray(key) != null) {
                JSONArray jArray = js1.getJSONArray(key);
                for (int i = 0; i < jArray.length(); i++) {
                    js1 = jArray.getJSONObject(i);
                }
                break;
            }
        }
    }
    return js1;
}

public static void main(String[] args) throws IOException, JSONException {
    FileInputStream inFile = new FileInputStream("/home/ermek/Internship/labs/java/task/test5.json");
    byte[] str = new byte[inFile.available()];
    inFile.read(str);
    String text = new String(str);
    JSONObject json = new JSONObject(text);
    setProperty(json, "rpc_server_type", "555");
    System.out.println(json.toString(4));
🌐
Medium
medium.com › @omarnyte › manipulating-nested-json-values-in-java-using-the-org-json-library-45df31fc4e46
Manipulating Nested JSON Values in Java Using the org.json Library | by Omar De Los Santos | Medium
September 3, 2018 - If neither of the base cases was met, that means that the key in the path matches a key/value pair in the current JSONObject. We’ll need to move into the nested JSONObject by updating jsonObject and keys before recursively calling the function.
🌐
YouTube
youtube.com › watch
How to Change Values in Nested JSON Objects | JSON Tutorial - YouTube
In this JSON tutorial, you will learn how to modify the values of nested JSON objects effectively. We'll explore various techniques and methods to update the...
Published   May 24, 2020
🌐
Quora
quora.com › How-do-you-change-the-value-of-a-nested-JSON-object-dynamically
How to change the value of a nested JSON object dynamically - Quora
Answer (1 of 2): Considering JS over here, you can dynamically modify the values of a JSON object in many ways. Let’s take the following example :- [code]let result = { "data":[ { "records":[ { "main":[ { "id":1, "name":"Geor...
🌐
Restack
restack.io › p › java-json-update-answer-nested-object-cat-ai
Java Json Update Nested Object | Restackio
Updating nested JSON objects in Java can be efficiently handled using libraries like Jackson and Gson. By following the steps outlined above, you can easily manipulate complex JSON structures, ensuring that your applications can handle dynamic data effectively.
🌐
YouTube
youtube.com › hey delphi
Array : How to update a nested JSON object in JSON file using Java? - YouTube
Array : How to update a nested JSON object in JSON file using Java?To Access My Live Chat Page, On Google, Search for "hows tech developer connect"As I promi...
Published   April 16, 2023
Views   37
Find elsewhere
🌐
GameSparks
support.gamesparks.net › support › discussions › topics › 1000081460
how to update specific nested json object? : GameSparks
We have a guide on how to do partial queries and updates to complex JSON objects such as yours. You can find it here.
🌐
Appsloveworld
appsloveworld.com › java › 100 › 1183 › fetch-and-update-nested-json-attribute-value
[Solved]-Fetch and Update Nested JSON attribute value-Java
While making and Android SDK, is there a way to constantly update the developer with a value without them passing in a view? Commit a single attribute value and not whole transaction · Java 8 Streams group by function, setting nested object's variable as key and parent object as value · Java create nested array, one array containing and array of arrays with key value pairs · How to get value from Firebase and save in an attribute using java code · null value when fetch image from json data using picasso
Top answer
1 of 2
4

JsonPath provides a convenient way of addressing nodes in json documents. JayWay is a good java implementation.

With JayWay:

DocumentContext doc = JsonPath.parse(json);
doc.set("level-1.level-2.level-3.level-4b[0].level-4b-3.StartDate", Instant.now().toString());
System.out.println(doc.jsonString());
2 of 2
2

If you are open to using Google's JSON library (https://github.com/google/gson), you can update nested elements and save them as shown in the following sample code:

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonObject;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.io.FileReader;
import java.nio.file.StandardOpenOption;

public class JsonUpdater {
  // Method to update nested json elements
  public void updateJson(String inputFile, String outputFile) {
      try {
          // Get the json content from input file
          String content = new String(Files.readAllBytes(Paths.get(inputFile)));

          // Get to the nested json object
          JsonObject jsonObj = new Gson().fromJson(content, JsonObject.class);
          JsonObject nestedJsonObj = jsonObj
                  .getAsJsonObject("level-1")
                  .getAsJsonObject("level-2")
                  .getAsJsonObject("level-3")
                  .getAsJsonArray("level-4b").get(0).getAsJsonObject();

          // Update values
          nestedJsonObj.addProperty("level-4b-1", "new-value-4b-1");
          nestedJsonObj.getAsJsonObject("level-4b-3").addProperty("StartDate", "newdate");

          // Write updated json to output file
          Files.write(Paths.get(outputFile), jsonObj.toString().getBytes(), StandardOpenOption.CREATE);
      } catch (IOException exception) {
          System.out.println(exception.getMessage());
      }
  }

  // Main
  public static void main(String[] args) {
    JsonUpdater jsonUpdater = new JsonUpdater();
    jsonUpdater.updateJson("test.json", "new.json");
  }
}

The above code reads json string from test.json, updates the values for level-4b-1 and StartDate (within level-4b-3), and saves the updated json string into new.json.

🌐
Stack Overflow
stackoverflow.com › questions › 65120717 › how-to-update-nested-json-in-java-with-dynamic-structure
How to update nested JSON in Java with dynamic structure - Stack Overflow
December 3, 2020 - I have a property file, where the user can define full field names, something like: league.firstname league.lastName Now in my code, I have an incoming JSON, and I want to first retrieve the exist...
🌐
Appsloveworld
appsloveworld.com › java › 100 › 652 › how-to-update-a-nested-json-object-in-json-file-using-java
[Solved]-How to update a nested JSON object in JSON file using Java?-Java
How to access object nested inside an array in MongoDB using Java driver · How to create a JSON file in a particular format in Java · Json Object conversion to java object using jackson · How to update a playlist using SoundCloud api wrapper for java
🌐
Stack Overflow
stackoverflow.com › questions › 72312455 › update-value-by-key-of-json-array-inside-nested-json-java
update value by key of json array inside nested json java - Stack Overflow
May 20, 2022 - String jsonInput = "{\n" + " \"sactions\": [\n" + " {\n" + " \"fund\": \"REAL\",\n" + " \"amount\": {\n" + " \"value\": 130.24,\n" + " \"curr\": \"RMB\"\n" + " },\n" + " \"type\": \"TD\",\n" + " \"desc\": \"TD\",\n" + " \"code\": \"PROMO\",\n" + " \"id\": \"deaedd69e3-6707-4b27-940a-39c3b64abdc7\"\n" + " }\n" + " ]\n" + "}"; String newJson = JsonPath.parse(jsonInput).set("$..id", "test").jsonString(); System.out.println(newJson); ... Agreed , but needed to work on Objects Mapper as this what they need.
🌐
Stack Overflow
stackoverflow.com › questions › 41020200 › updating-json-value-of-a-nested-json-array-in-a-json-file-java
updating json value of a nested json array in a json file | Java - Stack Overflow
Upon reaching that point, i am confused on how to update it so that it would reflect on file on filesystem. JSONParser parser = new JSONParser(); JSONArray rootArray = (JSONArray) parser.parse(new FileReader(pathToFile+fileName)); JSONObject project=null; for (Object rootEntry : rootArray) { project = (JSONObject) rootEntry; if( 1 == (Long) project.get("prjId")) { JSONArray issueArray = (JSONArray) project.get("issue"); for (Object issueEntry : issueArray) { JSONObject issue = (JSONObject) issueEntry; System.out.println((Long) issue.get("id")); if(2==(Long) issue.get("id")) { //now update the "comment" attribute here.
🌐
Cloudera Community
community.cloudera.com › t5 › Support-Questions › Replacing-characters-within-a-nested-json › m-p › 383454
Solved: Re: Replacing characters within a nested json - Cloudera Community - 383431
February 13, 2024 - The easiest way is to use ExecuteScript processor that parse the json as a map, then loop through each key and check if the value of that key is of type map as well- which means nested json - to then convert the map to json string and re assign back to the same key.
🌐
Stack Overflow
stackoverflow.com › questions › 58239462 › how-to-replace-update-nested-json-file-value-in-java
How to replace/update nested json file value in java? - Stack Overflow
October 4, 2019 - Seems odd that you're using both Jackson and org.json.JSONObject. I'd recommend using Jackson's tree model instead of org.json, and reading the json using ObjectMapper.readTree(File). Then you can navigate the tree and replace the fields you want to update.