Node JS JSON String And JavaScript Object Conversion Example Vice Versa

This example will show you how to convert JSON format string to JavaScript object and how to convert JS object back to JSON format string. It also show you how to write JSON string to a .json file and how to parse a json file content to a JavaScript object array.

1. Node JS JSON String And JS Object Convert Example Source File.

node js json string javascript object convert example source files

The account.json file is created in the example source code. The colors.json file is used to demo how to convert JSON file to javascript object array. The json_convert.js file is just the source node js file.

1.1 Source JS File.

json_convert.js

// Import fs module.
var fs = require("fs");

// Convert JSON format string to js object.
function stringToObject(JSONString) {

    var jsonObject = JSON.parse(JSONString);

    console.log("User Name : " + jsonObject.user_name);

    console.log("Password : " + jsonObject.password);

    console.log("Email : " + jsonObject.email);

    // Change email property value in JS object.
    jsonObject.email = '[email protected]';

    // Add qq and phone property in JS object.
    jsonObject.qq = '111111';
    jsonObject.phone = '13901234567';

    return jsonObject;
}

// Convert javascript object to json string.
function objectToString(jsObject) {

    var jsonString = JSON.stringify(jsObject);

    console.log("New JSON String : " + jsonString);

    return jsonString;
}

// Write json string to json file.
function writeJSONStringToFile(jsonString, filePath)
{
    // Create a write stream.
    var writeStream = fs.createWriteStream(filePath, {
        flags : "a"
    });

    writeStream.write(jsonString);

    writeStream.end('');
}

// Read json object from a json text file.
function jsonFileToArray(filePath){

    // This code will get a json object from a .json file.
    var jsonObject = require(filePath);

    // Get color json object array.
    var colorArray = jsonObject.colors;

    var arraySize = colorArray.length;

    for(var i=0; i<arraySize; i++)
    {
        var colorItem = colorArray[i];

        var color = colorItem.color;

        var category = colorItem.category;

        var type = colorItem.type;

        var code = colorItem.code;

        var rgba = code.rgba;

        var hex = code.hex;

        console.log("Color : " + color + " , Category : " + category + " , Type : " + type + " , Code Rgba : " + rgba + " , Hex : " + hex);
    }
}

// Create a new JSON string.
var jsonString = '{"user_name" : "Jerry Zhao", "password" : "888888", "email" : ["[email protected], [email protected]"]}';

// Get the json object by above string.
var jsonObject = stringToObject(jsonString);

// Change the js object property and convert to json string again.
var newJsonString = objectToString(jsonObject);

// Write the new json string to a json file.
writeJSONStringToFile(newJsonString, "account.json");

// Parse json data from a json file.
jsonFileToArray('./colors.json');

When you run above js code, you will get below output.

/usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/JSONStringObjectConvert/json_convert.js
User Name : Jerry Zhao
Password : 888888
Email : [email protected], [email protected]
New JSON String : {"user_name":"Jerry Zhao","password":"888888","email":"[email protected]","qq":"111111","phone":"13901234567"}
Color : white , Category : value , Type : undefined , Code Rgba : 0,0,0,1 , Hex : #FFF
Color : black , Category : hue , Type : primary , Code Rgba : 255,255,255,1 , Hex : #000
Color : red , Category : hue , Type : primary , Code Rgba : 255,0,0,1 , Hex : #FF0
Color : green , Category : hue , Type : secondary , Code Rgba : 0,255,0,1 , Hex : #0F0
Color : yellow , Category : hue , Type : primary , Code Rgba : 255,255,0,1 , Hex : #FF0
Color : blue , Category : hue , Type : primary , Code Rgba : 0,0,255,1 , Hex : #00F

Process finished with exit code 0

1.2 Generated account.json File.

account.json

{"user_name":"Jerry Zhao","password":"888888","email":"[email protected]","qq":"111111","phone":"13901234567"}

1.3 colors.json File.

colors.json

{
  "colors": [

    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },{
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    }

  ]
}
(Visited 1,248 times, 1 visits today)
READ :   Node JS Hello World Example With Eclipse

Leave a Reply

Your email address will not be published. Required fields are marked *

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