How to Write Json Data to a File

How do I write JSON data to a file?

data is a Python dictionary. It needs to be encoded as JSON before writing.

Use this for maximum compatibility (Python 2 and 3):

import json
with open('data.json', 'w') as f:
json.dump(data, f)

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:

import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)

See json documentation.

Write json into file Python 3

Assuming your json is like:

yourjson = [
{"AbandonmentDate": "", "Abstract": "", "Name": "ABC"},
{"AbandonmentDate": "", "Abstract": "", "Name": "ABC"}
]

then you need only to do this:

with open("outfile.txt", "w") as pf:
for obj in yourjson:
pf.write(json.dumps(obj) + "\n")

How do I save JSON to local text file

Node.js:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});

Browser (webapi):

function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');

How to write data to a JSON file using Javascript

You have to be clear on what you mean by "JSON".

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]. This one happens to be an array. If you want to add a new element to the array, just push it, as in

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

The word JSON may also be used to refer to a string which is encoded in JSON format:

var json = '[{"a": 1}]';

Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse:

var obj = JSON.parse(json);

Now you can manipulate the object any way you want, including push as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify:

var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'

JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify, and use another ajax call to send the data to the server for storage or other manipulation.

You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.

Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?

Write / add data in JSON file using Node.js

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
    table: []
    };
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
    if (err){
    console.log(err);
    } else {
    obj = JSON.parse(data); //now it an object
    obj.table.push({id: 2, square:3}); //add some data
    json = JSON.stringify(obj); //convert it back to json
    fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
    }});

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback).
With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

Write JSON to a File

makeJSONObject is returning JSONObject

Your code should be

saveCompo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setName();
createJSONFolder();
CompositionJso obj = new CompositionJso();
JSONObject jsonObject = obj.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
MyCompositionsListActivity.buildList();

try {
Writer output = null;
File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();

} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});

Write json object to .json file in JavaScript

JSON.stringify (introduced in ES 5.1) will convert the object into a string of JSON.

var json = JSON.stringify(proj);

JavaScript has no built-in mechanism for writing to a file. You generally need something non-standard provided by the host environment. For example, Node.js has the writeFile method of the File System module.

How to write a JSON file in C#?

Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:

  • .NET Core now has the spookily similar System.Text.Json serializer (see below)
  • The days of the JavaScriptSerializer have thankfully passed and this class isn't even in .NET Core. This invalidates a lot of the comparisons ran by Newtonsoft.
  • It's also recently come to my attention, via some vulnerability scanning software we use in work that Json.Net hasn't had an update in some time. Updates in 2020 have dried up and the latest version, 12.0.3, is over a year old (2021).
  • The speed tests (previously quoted below but now removed as they are so out of date that they seem irrelevant) are comparing an older version of Json.Net (version 6.0 and like I said the latest is 12.0.3) with an outdated .Net Framework serialiser.
  • One advantage the System.Text.Json serializer has over Newtonsoft is it's support for async/await

Are Json.Net's days numbered? It's still used a LOT and it's still used by MS libraries. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.



.NET Core 3.0+ and .NET 5+

A new kid on the block since writing this is System.Text.Json which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. I'd advise you to test this yourself .

Examples:

using System.Text.Json;
using System.Text.Json.Serialization;

List<data> _data = new List<data>();
_data.Add(new data()
{
Id = 1,
SSN = 2,
Message = "A Message"
});

string json = JsonSerializer.Serialize(_data);
File.WriteAllText(@"D:\path.json", json);

or

using System.Text.Json;
using System.Text.Json.Serialization;

List<data> _data = new List<data>();
_data.Add(new data()
{
Id = 1,
SSN = 2,
Message = "A Message"
});

await using FileStream createStream = File.Create(@"D:\path.json");
await JsonSerializer.SerializeAsync(createStream, _data);

Documentation



Newtonsoft Json.Net (.Net framework and .Net Core)

Another option is Json.Net, see example below:

List<data> _data = new List<data>();
_data.Add(new data()
{
Id = 1,
SSN = 2,
Message = "A Message"
});

string json = JsonConvert.SerializeObject(_data.ToArray());

//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);

Or the slightly more efficient version of the above code (doesn't use a string as a buffer):

//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
JsonSerializer serializer = new JsonSerializer();
//serialize object directly into file stream
serializer.Serialize(file, _data);
}

Documentation: Serialize JSON to a file

Fetch json data from url and write in a file

jsondata is a redundant variable. Here is a rewrite of your fetch().then().then() which leverages fs.writeFile() in the second .then().

I used node-fetch for this implementation, but it should work in a browser environment as well.

fetch('http://somewebsite.null')
.then((response) => {
return response.json();
})
.then((json) => {
fs.writeFile('./test.json', JSON.stringify(json), (err) => {
if (err) {
throw new Error('Something went wrong.')
}
console.log('JSON written to file. Contents:');
console.log(fs.readFileSync('test.json', 'utf-8'))
})
})

How to write a JSON to file in Java

import json.org and try this:

JSONObject json = new JSONObject(); //creates main json
json.put("Name", "sam");
json.put("Id", 1234);

JSONObject valuesJson = new JSONObject(); //another object
valuesJson.put("Car", "Maruti");

json.put("Values", valuesJson); //puts a json inside another

String jsonString = json.toString();

//next, saves the file:
PrintWriter out1 = null;
try {
out1 = new PrintWriter(new FileWriter("C:\\Users\\YOURNAME\\Documents\\json.txt"));
out1.write(jsonString);
} catch (Exception ex) {
System.out.println("error: " + ex.toString());
}

Don't forget to set the file path correctly!



Related Topics



Leave a reply



Submit