How to write an Object to a JSON file in Deno
In this tutorial, we are going to learn about writing a JavaScript Object to a JSON file in Deno using fs module.
Using the writeJson() method
The writeJson()
method is used to write the object to a JSON file in an asynchronous manner. It also creates a JSON file if the provided file path
doesn’t exist.
This method accepts two arguments, the first one is JSON file path
and the second one is an object
to write into that JSON file.
import { writeJson } from "https://deno.land/std/fs/mod.ts";
writeJson(
"./users.json",
{ name: "john", age: "22" }
);
To run the above code, we need to give write permissions to deno by using --allow-write
flag.
deno run --unstable --allow-write=./users.json app.js
The writeJson()
method also accepts options object as a third argument, if we pass spaces
property with value 2
it will add a formatted, easy to read JSON code to the file.
import { writeJson } from "https://deno.land/std/fs/mod.ts";
writeJson(
"./users.json",
{ name: "john", age: "22" },
{spaces: 2}
);
The users.json
file looks like this.
{
"name": "john",
"age": "22"
}
You can also tell, which object properties should be added to the JSON
file by passing it to a replacer
array.
import { writeJson } from "https://deno.land/std/fs/mod.ts";
writeJson(
"./users.json",
{ name: "john", age: "22", school: "st josh" },
{ spaces: 2, replacer: ["name", "age"] },
);
In the above code, we have added only two properties to the replacer
array, so that the output of the JSON file doesn’t contain school
property.
Using the writeJsonSync() method
The writeJsonSync()
method works similar like writeJson()
method, but it writes the object to a JSON file in a synchronous manner.
import { writeJsonSync } from "https://deno.land/std/fs/mod.ts";
writeJsonSync(
"./users.json",
{ name: "john", age: "22", school: "st josh" },
{ spaces: 2, replacer: ["name", "age"] },
);
Checkout, how to read a JSON file in deno.