How to NodeJS- working with JSON files

In this guide, we are going to learn how to use JSON files in Node.js programming. JSON is the most common data format used for asynchronous browser or server communication. Let’s look at JSON data in more detail.

JSON Data

JavaScript Object Notation (JSON) is a lightweight data-interchange format. It has been extended from the JavaScript scripting language and can be used with modern programming languages.

The following example shows how to use JSON to store a single contact information. JSON data is written as name/value pairs. A JSON file may include array, list, vector or sequence etc. If the JSON data describes an array, and each element of that array is an object.

JSON Data Example
     {
       "firstName": "Lauyou",
       "lastName": "Learning",
       "age": 30,
       "address": {
          "streetAddress": "Vadakkummuri",
          "city": "New York",
          "state": "NY",
          "postalCode": "10021-3100"
        },
        "phoneNumbers": [
          {
             "type": "home",
             "number": "212 555-1234"
          },
          {
             "type": "office",
             "number": "646 555-4567"
          },
          {
             "type": "mobile",
             "number": "123 456-7890"
          }
        ],
     }

 

Working with JSON files

Let’s figure out how to use JSON data on our Node.js project, Suppose we have following sample JSON data on our project. create a new file and save it as “sample.json” file.  This data about the tutorials of programming language category. It has the information about tutorials of each section like category id, name, description etc.

Sample.json
   {
     "categoryName": "Programming",
     "categories": [
        {
         "categoryID": "128",
         "parentID": "05",
         "subjectID": "04",
         "categoryName": "Java",
         "categoryDescription": "Java is a general-purpose computer programming language.",
         "AuthorID": "01"
        },
        {
         "categoryID": "185",
         "parentID": "05",
         "subjectID": "04",
         "categoryName": "PHP",
         "categoryDescription": "PHP is a server-side scripting language
         designed primarily for web development",
         "AuthorID": "01"
        },
        {
         "categoryID": "137",
         "parentID": "05",
         "subjectID": "04",
         "categoryName": "Node.js",
         "categoryDescription": "Node.js is an open-source, 
         cross-platform JavaScript runtime environment for developing",
         "AuthorID": "02"
        },
        {
         "categoryID": "121",
         "parentID": "05",
         "subjectID": "04",
         "categoryName": "Python",
         "categoryDescription": "Python is a widely used high-level programming language",
         "AuthorID": "02"
        },
        {
         "categoryID": "106",
         "parentID": "05",
         "subjectID": "04",
         "categoryName": "C Programming",
         "categoryDescription": "C is a powerful general-purpose programming language. ",
         "AuthorID": "01"
        }
     ]
   }

 

Following is the screenshot of “sample.json” file in our Node.js project. Here we stored all data in string format. you can store integers without double quotes.

JSON data in Node.js Express

 

To include our JSON data, we need to understand the local variables. Essentially, a local variable allows you to make variables that can use anywhere in our program. You can declare a local variable using the following syntax.

   app.locals.variable_name = "value";

 

Now, we are going to store our JSON data inside a local variable. Add the following line of code into “app.js” file. It references “sample.json” data into the local variable “SampleData”.

    app.locals.SampleData = require('./sample.json');

 

Let’s look how to display our Sample data on the home page. The following code will display the key value of the corresponding key from SampleData reference.

    SampleData.key

 

Add JSON data to a webpage

Now add the following code to index.jade to display our SampleData to the home page. To understand more about jade templating engine, read our guide.

index.jade
  //Render the category Name from sample.json file with header tag using reference.
  h2 #{sampledata.categoryName}

  //this loop iterate each key/value from categories array
  each item in sampledata.categories

    //Render the categoryName, categoryDescription and 
    //display Author Name using categoryID using switch
    h3= item.categoryName
    p= item.categoryDescription

    //switch statement display Author Name using categoryID
    case item.AuthorID
      when '01'
        p Author: Anwar YP
      when '02'
        p Author: Muhsin YP
      default
        p No Author

 

The each statement iterate over arrays and objects using our variable reference in jade. The item variable used to iterate through the elements of the categories. The case statement used above is a shorthand for JavaScript’s switch statement.

 

Following is the screenshot of “index.jade” file in our Node.js project.

Working with JSON files

 

Rerun the project server and preview it from your browser.

JSON files

 

Now we have “Programming” category as a parent object and loop through the JSON data and rendered each child category, description, and author.

 

Passing JSON data through Routes

We can pass the JSON data through routes to a specific page. In this section, we will learn how to pass JSON data through routes. You can use this method if you are writing code that is specific to a single page. In our example, we need to render data from “sample.json” only to the home page. so let’s go ahead and do that right now.

Remove the code app.locals.SampleData = require('./sample.json');  from “app.js” file.

Let’s make a new page local variable only for the home page. Open up “index.js” file from Route folder and add the following code.

    var sd = require('../sample.json');

Here, the ‘sample.json’ data referenced to the page local variable vd. The variable sd only has a page scope. that means you can only access it from the index page.

Whenever we render the index, we can pass through some additional values to the template. Let’s add the code sd : sampledata to the index router. Following will be our router code.

Route to Home
    /* GET home page. */
    router.get('/', function(req, res, next) {
      res.render('index', { 
         title: 'Express', 
         sampledata: vd
      });
    });

 

Following is the screenshot of “index.js” file in our Node.js project.

Working with JSON files

 

Now, Rerun the project server and preview it from your browser.

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...