CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Programming How To Work With JSON In Node.js / JavaScript

How To Work With JSON In Node.js / JavaScript

Rana Ahsan September 28, 2014 12 Comments


 How To Work With JSON In Node.js / JavaScript    

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

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

String To JSON Object:

This is very much easier and straight forward as below:

var jsonString = "{\"key\":\"value\"}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.key);

As you can see, we are using the built-in global JSON Object to parse a string which has JSON Data. Also, it might be 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));

Treat User Defined Class Instance To JSON String:

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

function MyClass(){
this.a = 'some value';
this.b = {
  'key': 'another json structure'
};
}

var instance = new MyClass();
console.log(JSON.stringify(instance));

However, you will need to be careful that you are declaring properties properly instead of declaring them as 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, I found a solution, which shows 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");

Here, NodeJS automatically read the file, parse 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';

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'];

Iterate Over A JSON Object:

Sometimes you will might need to traverse through each elements 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]);
}

However, the above code could give you error in case the value itself is a JSON object. So, you will might 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 have a specific key, we can check that with below approach:

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

Pretty Print JSON Object:

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

JSON.stringify(myObj, null, 2);

Same applies if you are trying to write the json object in a file with 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 know by commenting here. Happy coding 🙂

Related

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

About Rana Ahsan

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

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.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • LinQ Query With Like Operator
  • LinQ To SQL Database Update Operations In C#
  • Utilizing Config File In C#.NET Application
  • Get Facebook C# Api Access Token
  • Control HTML5 Audio With Jquery

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 · Streamline Pro Theme on Genesis Framework · WordPress · Log in