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.

Answer from SingleNegationElimination on Stack Overflow
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.

Top answer
1 of 1
3

Update

Oh seems I forgot to post the original json file. Pls put the student.json with below content: (Need to wrap with [ & ] to make it an array)

[{"name":"Mahesh","age":10}]

Because you can not just append objects to original object, it will violate JSON syntax, the way to make it correct is to put them into an array.

Original answer

You should change to use an array to store multiple objects. And use FileWriter to output.

Pls try this code, it works in my locl env:

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

import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.*;

public class JsonWritingProject {

    public static void main(String[] args) {
        JSONParser jsonParser = new JSONParser();

        try {
            Object obj = jsonParser.parse(new FileReader("D:\\student.json"));
            JSONArray jsonArray = (JSONArray)obj;

            System.out.println(jsonArray);

            JSONObject student1 = new JSONObject();
            student1.put("name", "BROCK");
            student1.put("age", new Integer(3));

            JSONObject student2 = new JSONObject();
            student2.put("name", "Joe");
            student2.put("age", new Integer(4));

            jsonArray.add(student1);
            jsonArray.add(student2);

            System.out.println(jsonArray);

            FileWriter file = new FileWriter("D:\\student.json");
            file.write(jsonArray.toJSONString());
            file.flush();
            file.close();

        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }

    }
}

And the library dependency is:

dependencies {
    compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'
}
Discussions

android - append data to existing JSON file - Stack Overflow
Yes, this is what I meant. The only difference is that on every pass I have to append ONE new object to an existing json file. Ending with two objects, before, was just an example. More on stackoverflow.com
🌐 stackoverflow.com
June 6, 2013
appending to json file : Forums : PythonAnywhere
def write_json(data, filename='answer.json'): with open(filename,'w') as f: json.dump(data, f, indent=2, ensure_ascii=False) with this code, I created the file answer.txt, which appears in my default directory (directory after home) The problem is, that I want to append to existing json file ... More on pythonanywhere.com
🌐 pythonanywhere.com
June 29, 2018
How to append JSON data to existing JSON file node.js - Stack Overflow
If you will append to the file a lot, csv might be a better choice than JSON. With JSON you have to read the whole file every time you edit it. ... Try this. Don't forget to define anchors array. var data = fs.readFileSync('testOutput.json'); var json = JSON.parse(data); json.push(...anchors); ... More on stackoverflow.com
🌐 stackoverflow.com
Appending JSON to same file
Hi, I need to make that within each request from api new dict will be appended to json. Now I have that each time data overwritten, but I need to append to existing file. How to achieve this? Code:(import requestsimport jsonimport timeimport csvimport pandas start=2 - Pastebin.com) More on discuss.python.org
🌐 discuss.python.org
0
0
January 5, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › python › append-to-json-file-using-python
Append to JSON file using Python - GeeksforGeeks
July 3, 2025 - import json # Function to append new data to JSON file def write_json(new_data, filename='data.json'): with open(filename, 'r+') as file: # Load existing data into a dictionary file_data = json.load(file) # Append new data to the 'emp_details' list file_data["emp_details"].append(new_data) # Move the cursor to the beginning of the file file.seek(0) # Write the updated data back to the file json.dump(file_data, file, indent=4) # New data to append new_employee = { "emp_name": "Nikhil", "email": "nikhil@geeksforgeeks.org", "job_profile": "Full Time" } # Call the function to append data write_json(new_employee)
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)
🌐
Finxter
blog.finxter.com › home › learn python blog › how to append data to a json file in python? [+video]
How to Append Data to a JSON File in Python? [+Video] - Be on the Right Side of Change
June 1, 2022 - Instead of opening the file object twice, you can open it only once and reset the file pointer using file.seek(0) to overwrite the existing file content using these four steps: Use open("your_file.json", "r+") to create a file object in reading and writing mode "r+". Call json.load(file) to load the data from the file in your Python code. Now, you can update the data in your Python code. For example, if you JSON file is structured as a list of dictionaries, simply append a new dictionary.
🌐
PythonAnywhere
pythonanywhere.com › forums › topic › 12985
appending to json file : Forums : PythonAnywhere
June 29, 2018 - with open('/home/***/answer.json') ... not parse as JSON anymore. Instead you need to read/parse it, then make changes to it's object representation as dicts/lists, then serialize back to string and (over)write the whole file....
🌐
ArduinoJson
arduinojson.org › version 6 › how to's › how to append a json object to a file?
How to append a JSON object to a file? | ArduinoJson 6
DynamicJsonDocument doc(8192); // Read the file File file = SPIFFS.open("/southpath.json", "r"); deserializeJson(doc, file); file.close(); // Append new element JsonObject obj = doc.createNestedObject(); obj["first_name"] = "Kenny"; obj["last_name"] = "McCormick"; // Write the file file = SPIFFS.open("/southpath.json", "w"); serializeJson(doc, file); file.close();
Find elsewhere
Top answer
1 of 2
5

Try this. Don't forget to define anchors array.

var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);

fs.writeFile("testOutput.json", JSON.stringify(json))
2 of 2
0

I created two small functions to handle the data to append.

  1. the first function will: read data and convert JSON-string to JSON-array
  2. then we add the new data to the JSON-array
  3. we convert JSON-array to JSON-string and write it to the file

example: you want to add data { "title":" 2.0 Wireless " } to file my_data.json on the same folder root. just call append_data (file_path , data ) ,

it will append data in the JSON file, if the file existed . or it will create the file and add the data to it.

data = {  "title":"  2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )

the full code is here :

   const fs = require('fs');
   data = {  "title":"  2.0 Wireless " }
   file_path = './my_data.json'
   append_data (file_path , data )

   async function append_data (filename , data ) {

    if (fs.existsSync(filename)) {
        read_data = await readFile(filename)
        if (read_data == false) {
            console.log('not able to read file')
        }
        else {
            read_data.push(data)
            dataWrittenStatus = await writeFile(filename, read_data)
            if dataWrittenStatus == true {
              console.log('data added successfully')
            }
           else{
              console.log('data adding failed')
            }
        }
      else{
          dataWrittenStatus = await writeFile(filename, [data])
          if dataWrittenStatus == true {
              console.log('data added successfully')
          }
          else{
             console.log('data adding failed')
           }
      }
   }



    async function readFile  (filePath) {
      try {
        const data = await fs.promises.readFile(filePath, 'utf8')
        return JSON.parse(data)
      }
     catch(err) {
         return false;
      }
    }

    async function writeFile  (filename ,writedata) {
      try {
          await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
          return true
      }
      catch(err) {
          return false
      }
    }
🌐
Python.org
discuss.python.org › python help
Appending JSON to same file - Python Help - Discussions on Python.org
January 5, 2023 - Hi, I need to make that within each request from api new dict will be appended to json. Now I have that each time data overwritten, but I need to append to existing file. How to achieve this? Code:(import requestsimpor…
🌐
Delft Stack
delftstack.com › home › howto › python › append data to a json file using python
How to Append Data to a JSON File Using Python | Delft Stack
February 2, 2024 - This tutorial demonstrates the use of Python dictionary and list to append data to a JSON file using Python.
🌐
GitHub
github.com › jprichardson › node-jsonfile › issues › 84
Possibility to append JSON data to existing JSON file. · Issue #84 · jprichardson/node-jsonfile
July 24, 2017 - Can we add some elements to an already existing JSON file? my.json [ { "name": "FY2017 Postage Services", "description": "NA" }, { "name": "Rugged iPad Cases", "description": "NA" } ] my-new [ { "name": "FY2037 Postage Services", "descri...
Author   niksmac
🌐
Stack Overflow
stackoverflow.com › questions › 74730572 › how-to-append-json-object-data-to-existing-json-file-by-html-input-form
How to append JSON object data to existing JSON file by html input form?
December 8, 2022 - Make any changes you want and then re-stringify and write to the file. ... You can't with javascript only, Javascript is a client-side language, it has no access to make write operations on the OS, you also need a server-side language to do that for example Nodejs. ... Read JSON from URL. E.g. $.getJSON('WordMeanings.json', successCallback) ... function successCallback(data) { data.WordMeanings.push({ "bangla": "ki obostha?", "example": "What's up?"
🌐
Stack Overflow
stackoverflow.com › questions › 70168189 › append-data-to-an-existing-json-file-in-nodejs
node.js - append data to an existing Json file in nodejs - Stack Overflow
November 30, 2021 - i'm trying to add new data in an existing json file named db.json which i use to store data locally aka inMemory.So i tried many ways to achieve that but still not working as expected Since the add operation replaced the existing data.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Append an object to an existing JSON file - JavaScript
April 18, 2024 - I’m relatively new to JS. I am working on a simple webpage which gets an input from user and manipulates it, and finally returns it as an object. What I want is, to append my output objects to my existing .json file, ea…
🌐
TutorialsPoint
tutorialspoint.com › how-to-add-a-json-string-to-an-existing-json-file-in-java
How to add a JSON string to an existing JSON file in Java?
import java.io.*; import java.util.*; import com.google.gson.*; import com.google.gson.stream.*; import com.google.gson.annotations.*; public class JSONFilewriteTest { public static String nameRead; public static void main(String[] args) { try { JsonParser parser = new JsonParser(); Object obj = parser.parse(new FileReader("employee1.json")); JsonObject jsonObject = (JsonObject) obj; System.out.println("The values of employee1.json file:\n" + jsonObject); JsonArray msg = (JsonArray)jsonObject.get("emps"); Iterator<JsonElement> iterator = msg.iterator(); while(iterator.hasNext()) { nameRead = i