by Sai gowtham

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.

app.js
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.

app.js
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.

users.json
{
  "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.

app.js
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.

app.js
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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course