Use [] to access a dynamic key on the object

json.users[username] = {a: 1, b: 2}

Be careful naming your variable like that tho because json the way you're using it is not JSON. JSON is a string, not an object with keys.

See the below demo for distinction

var json = '{"users":{"test1":{},"test2":{}}}';
var obj  = JSON.parse(json);
var newuser = 'test3';
obj.users[newuser] = {};
console.log(JSON.stringify(obj));
//=> {"users":{"test1":{},"test2":{},"test3":{}}}

Answer from Mulan on Stack Overflow
🌐
tutorialpedia
tutorialpedia.org › blog › how-to-add-a-new-object-to-an-existing-json-file
How to Add a New Object to an Existing JSON File: Automate and Fix Formatting Issues (Ensure Proper Array Structure) — tutorialpedia.org
import json # Path to your JSON ... json.load(file) # Parses JSON into a Python dict/list · Identify the array in the JSON data where you want to add the new object....
Discussions

Insert json object into existing Json array
I have created a tool to insert JSON objects with several rules: Read the product status, and then insert based on the status If there is no data in this status, then insert the object If there is... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
Add new attribute (element) to JSON object using JavaScript - Stack Overflow
How do I add new attribute (element) to JSON object using JavaScript? More on stackoverflow.com
🌐 stackoverflow.com
python - How to append data to a json file? - Stack Overflow
It's easier to add new data in a list and you would not break your JSON format. ... json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must ... More on stackoverflow.com
🌐 stackoverflow.com
python - How to add data to a already existing json object without overwriting existing data - Stack Overflow
I make a baseline for what the data inside the json object and its keys. What i am trying to do is to save the data i have collected in the function to the json object. I am very unsure on how i add that new data to the json data without overwriting any existing data already present in the ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Postman
community.postman.com › help hub
Add an object to existing json - Help Hub - Postman Community
January 29, 2021 - I want to add an object(key value pair) to a payload that i am getting from the external data file. “payload”:"{“key1”:“value1”,“key2”:“value2”,“key3”:“value3”}" What I want to do is add (“key4”:“value4”) to the payloa…
🌐
Educative
educative.io › answers › how-to-add-data-to-a-json-file-in-javascript
How to add data to a JSON file in JavaScript
Line 18: Convert the JavaScript object back into a JSON string. Lines 20–23: Write updated data into the file, data.json, using the writeFileSync() method. Lines 25–27: Prints the content of the updated data.json file.
🌐
Baeldung
baeldung.com › home › scripting › adding field to a json object
Adding Field to a JSON Object | Baeldung on Linux
March 18, 2024 - The program uses the JSON module with its encode_json and decode_json methods to transform the objects. Thus, after reading the file, it adds the new attribute to the fruit object, using the object reference syntax. Likewise, we can use a Perl script to add a new object to an existing JSON object:
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › how-to-add-data-in-json-file-using-node-js
How to Add Data in JSON File using Node.js ? - GeeksforGeeks
July 23, 2025 - This will be done using · JSON.stringify() method. var newData = JSON.stringify(myObject); fs.writeFile('data.json', newData, err => { // error checking if(err) throw err; console.log("New data added"); });
Find elsewhere
Top answer
1 of 12
105

json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.

Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.

Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.

2 of 12
54

You probably want to use a JSON list instead of a dictionary as the toplevel element.

So, initialize the file with an empty list:

with open(DATA_FILENAME, mode='w', encoding='utf-8') as f:
    json.dump([], f)

Then, you can append new entries to this list:

with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
    entry = {'name': args.name, 'url': args.url}
    feeds.append(entry)
    json.dump(feeds, feedsjson)

Note that this will be slow to execute because you will rewrite the full contents of the file every time you call add. If you are calling it in a loop, consider adding all the feeds to a list in advance, then writing the list out in one go.

🌐
Stack Overflow
stackoverflow.com › questions › 74665910 › how-to-add-new-data-to-existing-json-file-in-java
arrays - how to add new data to existing json file in java - Stack Overflow
JSONObject root = new JSONObject(); JSONArray questions = new JSONArray(); JSONObject question1 = createQuestion( "q1", "2", "1", "animal", "answer1", "answer2", "answer3", "answer4" ); JSONObject question2 = createQuestion( "q2", "1", "2", "animal", "answer1", "answer2", "answer3", "answer4" ); Collections.addAll(questions, question1, question2); root.put("questions", questions);
🌐
Tutorial Republic
tutorialrepublic.com › faq › how-to-add-new-property-to-json-object-using-javascript.php
How to Add New Property to JSON Object Using JavaScript
// Store JSON string in a JS variable var json = '{"name": "Harry", "age": 18}'; // Converting JSON-encoded string to JS object var obj = JSON.parse(json); // Adding a new property using dot notation obj.gender = "Male"; // Adding another property using square bracket notation obj["country"] = "United States"; // Accessing individual value from JS object document.write(obj.name + "<br>"); // Prints: Harry document.write(obj.age + "<br>"); // Prints: 14 document.write(obj.gender + "<br>"); // Prints: Male document.write(obj.country + "<br>"); // Prints: United States // Converting JS object back to JSON string json = JSON.stringify(obj); document.write(json);
🌐
n8n
community.n8n.io › questions
Inserting Data into existing JSON - Questions - n8n Community
November 28, 2022 - Describe the issue/error/question I prepped a “template” file, that I load in via Binary Read and need to append some data into a certain spot. My Json looks like this { "Categories": [ { "name": "Default", "name": "Another Category" } ], "Data": [NEED DATA HERE] } The data that I need ...
🌐
EyeHunts
tutorial.eyehunts.com › home › how to add json object to existing json array in javascript | example
How to add JSON object to existing JSON array in JavaScript | Code
November 23, 2022 - var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}; var data = []; data.push(feed); console.log(data); If you have multiple objects then do iterate the object. var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}; var data = []; for(var i in my_json) { data.push(my_json[i]); } console.log(data);
🌐
Make Community
community.make.com › questions
Add a new value to an existing JSON - Questions - Make Community
June 28, 2023 - Hi, I am trying to add a value that I always need to add to an existing JSON. The thing is that my JSON is created and parsed, but I haven’t had any success using the module “Text aggregator” I need to add a new val…
🌐
Quora
quora.com › I-want-to-add-a-new-JSON-object-to-the-already-existing-JSON-Array-What-are-some-suggestions
I want to add a new JSON object to the already existing JSON Array. What are some suggestions? - Quora
Answer (1 of 5): Simply use push method of Arrays. [code]var data = [ { name: "Pawan" }, { name: "Goku" }, { name: "Naruto" } ]; var obj = { name: "Light" }; data.push(obj); console.log(data); /* 0:{name:"Pawan"} 1:{name: "Goku"} 2:{name: "Naruto"} ...
Top answer
1 of 2
2

I found the solution, thanks to the comments by other users and to a "retired" answer, not present here anymore. Maybe it was my fault not being clear.

public void addEntryToJsonFile(Context ctx, String id, String name, String size) {

    // parse existing/init new JSON 
    File jsonFile = new File(ctx.getDir("my_data_dir", 0), "my_json_file.json");
    String previousJson = null;
    if (jsonFile.exists()) {
        try {
            previousJson = Utils.readFromFile(jsonFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        previousJson = "{}";
    }

    // create new "complex" object
    JSONObject mO = null;
    JSONObject jO = new JSONObject();

    try {
        mO = new JSONObject(previousJson);
        jO.put("completed", true);
        jO.put("name", name);
        jO.put("size", size);
        mO.put(id, jO); //thanks "retired" answer
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // generate string from the object
    String jsonString = null;
    try {
        jsonString = mO.toString(4);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // write back JSON file
    Utils.writeToFile(jsonFile, jsonString);

}
2 of 2
1

Edited after dentex comment

  1. Read your file
  2. Parse the root Json object
  3. If the root object not is already a complex object
    1. Create a new root object
    2. put your root object in it
  4. put your second object in the root object
  5. Write bnack your file

in pseudo code:

oldJson = ParseJsonFromFile()
newJson = {"item1": true, "item2": "abcde" ...}
JSONObject root;
if (oldJson.hasKey("pass1") {
    root = oldJson
} else {
    root = new JSONObject()
    root.add("pass1", oldJson)
}
root.add("pass" + root.getSize() + 2, newJson)
WriteJsonToFile(root)
🌐
Stack Overflow
stackoverflow.com › questions › 62255156 › how-to-add-new-object-to-an-existing-json-data
reactjs - how to add new object to an existing json data - Stack Overflow
June 8, 2020 - so what i'm doing is that i want the form to take these data and add them to the existing json data that have been loaded internally how can i do that? i'm really stuck and no idea how to do it ... const [photo,setPhoto] = useState([]) const newPhotosLocally = photo newPhotosLocally.forEach((item,i) =>{ item.photoId = i +1; }) console.log(newPhotosLocally) useEffect(() => { axios.get("https://jsonplaceholder.typicode.com/photos").then( result => { setPhoto(result.data) } ) },[])