How to insert into json file without deleting the previous data?

append to json file python
javascript read json file
does json dump overwrite

I am insert data into .json file. My insertion works fine, but I have a problem - when I insert new data, the previous data in the file is deleted. How can I manage that? Also I would need it to be in the format of because I need to query it:

[
  {
    "Rollnumber": 3,
    "StudentName": "Tapas"
  },
  {
    "Rollnumber": 4,
    "StudentName": "Papas"
  }
]

When I pass the data as the list.ToArray()(that would be the _data in the code example) I get the [] brackets, but only on the first data with rollnumber = 3. This is my code so far:

private void AddStudent()
{
    Student objStudent = new Student();
    objStudent.Rollnumber = 3;
    objStudent.StudentName = "Tapas";


    /*  List<Student> _data = new List<Student>();
    _data.Add(new Student()
    {
        Rollnumber = 4,
        StudentName = "Papas"
    });
    */

    string jsonData = JsonConvert.SerializeObject(objStudent, Formatting.Indented);
    System.IO.File.WriteAllText(jsonFileS, jsonData);
}

I have tried with the StreamWritter also, but I could not do it.

  1. Retrieve the source file that containing JSON.
  2. Read text content (JSON data) from source file.
  3. Deserialize JSON data to List of student object.
  4. Add new student student list.
  5. Serialize the student list, you will get JSON data string as return from that method.
  6. Save JSON string to the source file.

Here is example code:

var file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
var jsonString = await FileIO.ReadTextAsync(file);
var studentList = JsonConvert.DeserializeObject<List<Student>>(jsonString);
var newStudent = new Student();
newStudent.Rollnumber = 2;
newStudent.StudentName = "Abcd";
studentList.Add(newStudent);
var updatedJsonString = JsonConvert.SerializeObject(studentList);
await FileIO.WriteTextAsync(file, updatedJsonString);

How to insert into json file without deleting the previous data?, I am insert data into .json file. My insertion works fine, but I have a problem - when I insert new data, the previous data in the file is deleted. First of all we create a HTML file that can be used to send the stringifyed JSON data to a Node server using AJAX post request. We will also create a server side app that listens to the post requests, extracts the JSON and insert in to the database. This app uses the modules body-parser and mysql.

I think in your situation, you can do a little trick like :

1, Read data from file

StreamReader sw = new StreamReader(fileName);
string res = sw.ReadToEnd();

2, Remove the "]" of the "res"(res variable) and add new Json string(remove the "[" and add ",") with your format.

So your string will look like two strings bellow adding together

[
  {
    "Rollnumber": 3,
    "StudentName": "Tapas"
  }
// Cut the last "]"

and

// cut the first "[" and add ","
      ,
      {
        "Rollnumber": 4,
        "StudentName": "Papas"
      }
    ]

So it will become what you want in the final :

[
  {
    "Rollnumber": 3,
    "StudentName": "Tapas"
  },
  {
    "Rollnumber": 4,
    "StudentName": "Papas"
  }
]   

How to append to a JSON file in Python, How do I add data to a JSON file in Python? In this tutorial, you will learn how to use GoAnywhere Managed File Transfer to read data from JSON files and load that data into RowSet variables using the Read JSON task. Those RowSets can then be used to insert the data into a database or translate the data to another file type such as XML, Excel, fixed-width, or CSV with no coding required.

The answer is on this link : append to a json file

   var jsonData = System.IO.File.ReadAllText(jsonFile);
        // De-serialize to object or create new list
        var employeeList = JsonConvert.DeserializeObject<List<Student>>(jsonData)
                              ?? new List<Student>();

        // Add any new employees
        employeeList.Add(new Student()
        {
            Rollnumber = 1,
            StudentName = "Paja1",
            Subject = new Subject
            {
                Id = 1,
                Name = "Sub1"
            }
        });
        employeeList.Add(new Student()
        {
            Rollnumber = 1,
            StudentName = "Pera1",
            Subject = new Subject
            {
                Id = 1,
                Name = "Sub1"
            }
        });

        // Update json data string
        jsonData = JsonConvert.SerializeObject(employeeList,Formatting.Indented);
        System.IO.File.WriteAllText(jsonFile, jsonData);

How to validate a JSON file format · SIMRacingApps , as type" to text, then Notepad tacks on a . Write Data to Local JSON File using Node.js . November 11th, 2016 First, we need to have a JSON file with empty array or existing array with objects.

As I mentioned in my comments to your question, you need to either load the entire file, deserialize it and then add items to it in memory. Once done, rewrite to the file by serializing it.

If you do not want to load the entire file into memory, then work with the file manually by manipulating the serialized string and then append to the file; else you will end up with bad JSON in file.

Here is the first method wherein you deserialize the entire file:

public static class Program
{
    public static void Main()
    {
        var rolls = LoadRolls();

        // Once the contents of the file are in memory you can also manipulate them         
        Roll firstRoll = rolls.SingleOrDefault(x => x.Rollnumber == 1);
        if (firstRoll != null)
        {
            firstRoll.StudentName = "Jerry";
        }

        // Let's just add a few records. 
        rolls.AddRange(
            new List<Roll>{
                new Roll { Rollnumber = 1, StudentName = "Elaine" },
                new Roll { Rollnumber = 2, StudentName = "George" }
            });

        string json = JsonConvert.SerializeObject(rolls, Newtonsoft.Json.Formatting.Indented);

        File.WriteAllText("Rolls.txt", json);

        Console.Read();
    }

    private static List<Roll> LoadRolls()
    {
        List<Roll> rolls = JsonConvert.DeserializeObject<List<Roll>>(File.ReadAllText("Rolls.txt"));

        return rolls ?? new List<Roll>();
    }
}

public class Roll
{
    public int Rollnumber { get; set; }
    public string StudentName { get; set; }
}

Saving Text, JSON, and CSV to a File in Python, If you wanted to write and then read from a file, without deleting the previous contents then function to put data in a sequence (like a list or tuple) and into a file: JSON is in an array format which holds the key-value pairs. We can do this by using JSON simple library. Just download the library from below and add this library to your eclipse java project where you will make class to read and write JSON file. Step 1: To write JSON File. Here, first we will create a JSON file and write some data in it.

Appending data to JSON txt file without overwriting : learnpython, The current script works but it overwrites the data within the txt file every time the [deleted]. 1 point · 1 year ago. I want it to add the new data to the JSON txt file then txt file as its doing now but without overwriting any previous data on the file. to find a "top of the line programming computer" as my boss apparently put it. When you want to add new data to JSON, or change existing data, you should load the source file, then update the data and save the new values. JSON is not a format that allow a simple "append" (this is possible only in a few formats e.g. CSV) .

PHP file_put_contents() Function, Write the data into the file; Close the file and release any locks. Note: Use FILE_APPEND to avoid deleting the existing content of the file. Syntax. file_put_contents  Mongoose – Insert Document to MongoDB. Insert Document to MongoDB – To insert a single document to MongoDB, call save() method on document instance. Callback function(err, document) is an optional argument to save() method. Insertion happens asynchronously and any operations dependent on the inserted document has to happen in callback function for correctness.

Python Read File, Write File, Open File, Delete File, Copy File , If you open a file in write mode, the previous data stored into that fill will be erased. read() : This function reads the entire file and returns a string; readline() : This  In the second case, we can get the metadata from the table instead of the JSON file in order to do this. Reading the JSON Data into an NVARCHAR(MAX) Variable. This should work to read in the data from a file that is local to the server, but it doesn’t seem to import utf-8 data properly. However, for this test harness, it is OK.

Comments
  • You could use File.AppendAllText(jsonFileS, jsonData); instead. It'll append to the file if it does exist or create a new one otherwise.
  • When you want to add new data to JSON, or change existing data, you should load the source file, then update the data and save the new values. JSON is not a format that allow a simple "append" (this is possible only in a few formats e.g. CSV). How to do this? This depends on the JSON framework you use.
  • @Julo do you have some example on how to do it?
  • Your file has an array, if you append to it, you will have an array and whatever else you appended to it. If you always need one array in the file, Everytime you need to modify the file, desrialize the contents of the file into a list, add to the list، then serialize the entire list back to the file.
  • Unfortunately I do not know the JSON library your are using. And i'm afraid, it is not possible with a library meant for serialisation of classes (at least not without deserialising of the previous content).
  • This is something like a solution that I have posted. Thanks
  • Actually i didn't see that... Sorry
  • Yeah,that is one way to do it! :)
  • I don't want to DeserializeObject json string because it will take a lot of time if your json string is too long, so this trick I think it is better.
  • @Alexander: but remember, this will only add new data and it will work only when there is no 'new line' character in the file (when there is a new line character, you need to remove more character until it will reach the ] character). And most important thing is, that this can be used only to append new data. It will not reflect changes in existing data (new values in existing records).