• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / How To Work With JSON In Node.js / JavaScript

How To Work With JSON In Node.js / JavaScript

September 28, 2014 by Rana Ahsan 12 Comments

nodejs json

Recently I started learning and working on the Node.js platform. So, now I am again brushing up on my long-forgotten JavaScript skill. JSON is a common format you face every now and then in JavaScript, whether it’s on the client side or server side. As NodeJs is a server-side platform, it has a little more capability than browser-based JavaScript, like writing to file systems, etc.

I am trying to aggregate most of the operations that we can usually perform related to a JSON object. Though most of this tutorial will apply to both kinds of JavaScript, few could be specific to Node.js.

String To JSON Object:

This is very much easier and straightforward as below:

var jsonString = "{\"key\":\"value\"}"; var jsonObj = JSON.parse(jsonString); console.log(jsonObj.key);<br>
Code language: JavaScript (javascript)


As you can see, we are using the built-in global JSON Object to parse a string that has JSON Data. Also, it might be a good idea to use “.trim()” method on the string, if you think there might be some chance of extra space, etc in the JSON string. Otherwise, it won’t get parsed and you will face an unexpected error.

JSON Object To String:

As like the previous case, we can use the same global object’s ‘stringify’ method to convert a given JSON to string data. This can be done easily as like below:

var jsonObj = {'key':'value'}; console.log(JSON.stringify(jsonObj));
Code language: JavaScript (javascript)

Treat User-Defined Class Instance To JSON String:

If you are writing JavaScript OOP style and want to convert an object instance to a JSON-like string(with its attributes name/value as key/value), You still can use the same JSON object-to-string approach as below:

<br> function MyClass(){ this.a = 'some value'; this.b = { 'key': 'another json structure' }; } var instance = new MyClass(); console.log(JSON.stringify(instance));
Code language: JavaScript (javascript)

However, you will need to be careful that you are declaring properties properly instead of declaring them as a local variable. This stack-overflow thread might also help in understanding the differences easily.

Read JSON From File System In NodeJS:

At first, I tried googling about it, and I found a solution, which shows an example with file system support of nodejs(fs module). But, I don’t really see any meaning of that at all, as we can simply do the same thing by:

var jsonObj = require("./path/to/myjsonfile.json");
Code language: JavaScript (javascript)


Here, NodeJS automatically read the file, parses the content to a JSON object, and assigns that to the left-hand side variable. It’s as simple as that!

Add New Element To Existing JSON Object:

Say, you have an existing JSON object, which you want to modify to add new key/value pair(s). You can do that using either of the two ways as below:

var myJson = {'key':'value'}; //new element myJson.key2 = 'value2'; //or myJson[key3] = 'value3';
Code language: JavaScript (javascript)

Delete An Element From A JSON Object:

Well, to delete an element from a JSON object, it can be done by using the ‘delete’ keyword. An example is given below:

var myJson = {'key':'value'}; delete myJson['key'];
Code language: JavaScript (javascript)

Iterate Over A JSON Object:

Sometimes you will need to traverse through each element of the JSON object. This can be done in a for loop easily as like below:

var myJson = {'key':'value', 'key2':'value2'}; for(var myKey in myJson) { console.log("key:"+myKey+", value:"+myJson[myKey]); }
Code language: JavaScript (javascript)


However, the above code could give you an error in case the value itself is a JSON object. So, you will want to check whether the value is itself json or not and handle it thereby.

Check Key Existence:

If at some point we need to check whether a JSON object has a specific key, we can check that with the below approach:

var myJson = {'key':'value', 'key2':'value2'}; if(myJson.hasOwnProperty('key2')){ //do something if the key exist }
Code language: JavaScript (javascript)

Pretty Print JSON Object:

In debugging, we always like to print data to the console to verify if it’s OK. If you are trying to see if a large JSON has something you are expecting, then it’s very hard to locate if it’s printed in a flat structure. In such cases, what you need is pretty much printing the JSON object. Here is the javascript code snippet that will do the trick:

JSON.stringify(myObj, null, 2);
Code language: JavaScript (javascript)


The same applies if you are trying to write the JSON object in a file with a pretty printed format.

Comparing Two JSON Objects:

If you need to compare two JSON objects to check if they are equal or not, it’s better to iterate over and compare each property. As a reference, please visit this stack-overflow thread.

Anything Else?

If you think anything is missing or something isn’t clear about using JSON data in node.js / JavaScript, please ask me to know by commenting here. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: javascript, json, nodejs

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. Garcia says

    December 9, 2014 at 9:19 pm

    Nice post, first time i see someone explain how to read json files with the require() function on node.
    That is handy!

    Thanks!

    Reply
    • Garcia says

      December 9, 2014 at 9:25 pm

      Also a nice addition would be how to prettify a JSON string, found an answer for that here: http://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript

      Reply
  2. Monis says

    April 20, 2015 at 4:28 am

    Nice tutorial
    I am getting data from server
    success:function(response)
    {

    alert(JSON.stringify(response));
    }

    Which is a string, and I want to change in it object to populate my html element
    How I can do with parse?

    Reply
    • Mohammad Saif says

      February 19, 2020 at 2:19 am

      var data = JSON.parse(body_your_response);

      this will parse into a json object and you can pass it while rendering blade.

      Reply
  3. joy says

    May 21, 2015 at 4:26 pm

    I’m new to Javascript and am struggling with something that should be quite simple. When I found your tutorial I was delighted. The first little bit is exactly what I want to do. However, I’m using nodejs rather than pure javascript. Perhaps that is problem.

    Here are the results I’m getting with your first example:

    var jsonString = “{‘key’:’value’}”;
    undefined
    > var jsonObj = JSON.parse(jsonString);
    SyntaxError: Unexpected token ‘
    at Object.parse (native)
    at repl:1:20
    at REPLServer.self.eval (repl.js:110:21)
    at repl.js:249:20
    at REPLServer.self.eval (repl.js:122:7)
    at Interface. (repl.js:239:12)
    at Interface.emit (events.js:95:17)
    at Interface._onLine (readline.js:203:10)
    at Interface._line (readline.js:532:8)
    at Interface._ttyWrite (readline.js:761:14)

    Running the json through jsonlint shows that it’s not valid unless it has double quotes, however, nodejs won’t accept doublequotes in my variable statement.

    Can you tell me what is wrong and how I can get around it?

    Reply
    • Md Ali Ahsan Rana says

      May 21, 2015 at 10:30 pm

      Hi Joy, glad to hear that you liked this tutorial. Also, thanks for your point. It was an error in my example, there will be double quote inside and need to be escaped(via \ char ). I have corrected it and now should work for you. Hope this helps.

      Reply
  4. Arun Stefen says

    October 19, 2015 at 6:26 am

    how to check the repetition of a same key on a json file..

    Reply
  5. Mudassirkhan Pathan says

    February 12, 2016 at 12:16 pm

    Consider I have a string formatted in such a way that I can easily parse it using JSON.parse() of JS. But the string contains repeating key, representing similar significance but with different values. And I want to handle both values of those keys… that I will, while parsing(if I could handle them separately), either store the values in list or store with different keys at my end. So I wanted to ask how I can get access to those values of repeating keys.

    Reply
  6. jyo says

    May 4, 2016 at 5:31 am

    How to print json keys through node js program?

    Reply
  7. Julie Alary (@julie_alary) says

    September 11, 2018 at 4:07 am

    it’s hard to find simple explanations ! Many thanks !

    Reply
  8. NganKhuong says

    December 11, 2018 at 3:02 am

    Could you share the way to update value of an element node in Json Object?

    Reply
  9. Khalid says

    April 21, 2019 at 9:17 am

    Hi Rana,

    if you can help me with this ? i want to read only the “output” “xReturnMsg” value in node.js application out of the following which is returned from a SQL Server Stored Proc.
    {
    “recordsets”: [],
    “output”: {
    “xReturnMsg”: “A04C4F2D-9D04-42AE-8690-F705827EE042”
    },
    “rowsAffected”: [],
    “returnValue”: 0
    }

    can you please help me.

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Getting Started With Smarty Template Engine
    Getting Started With Smarty Template Engine
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • LinQ To SQL Database Update Operations In C#
    LinQ To SQL Database Update Operations In C#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023