Converting JSON Object to String and String to JSON Object

Converting JSON Object to String and String to JSON Object

In this article, I am going to discuss How to Convert JSON Object to String and String to JSON Object with Examples. Please read our previous article, where we discussed Working with JSON Object. At the end of this article, you will understand everything about How to Convert JSON Object to String and String to JSON Object.

What is a JSON String?

JSON is an acronym for JavaScript Object Notation.  JSON was designed as a data interchange format and has a syntax that is a subset of JavaScript. Context which is surrounded by quotes (single or double), loaded from a text file, etc. are called JSON strings.

Example: {“id”:1, “name”:”John”, “age”:22, “eyecolor”:”Blue”, “profession”:”Accountant”}

JSON is interoperable meaning that it’s language/platform independent. The JSON format is used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and mobile/web application, serving as an alternative to XML. 

When would you want to convert from JSON Object to JSON string?

A common use of JSON is to exchange data to/from a web server. When sending data to a web server, the data has to be a string. Then we have to convert a JSON object into a string with JSON.stringify().

Syntax:

Use the JavaScript function JSON.stringify() to convert JSON Object (JSON Array) it into a string.
var jsonString = JSON.stringify(obj);

Example: Converting JSON Object to JSON String

In the below example, we have one JSON object i.e. employee. We are converting that JSON Object into a JSON string and printing that JSON String on the console. Notice that we are also printing the Data type of the JSON String.

<!DOCTYPE html>
<html>
<head>
    <title>Converting JSON Object to JSON String</title>
</head>
<body>
  <h3>Converting JSON Object to JSON String</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    const employee= {
      "firstname": "Rick",
      "lastname": "Brown",
      "age": 22,
      "salary": 15000
    };
    var string = JSON.stringify(employee);
    console.log(string);
    console.log(typeof string);
  </script>
</body>
</html>

Now run the above code and open the browser developer tool by pressing the F12 key and look at the Console tab where it logs the JSON string ({“firstname”:”Rick”, “lastname”:”Brown”, “age”:22, “salary”:15000}) and the data type of the JSON string (string).

When would you want to convert from JSON Object to JSON string?

Example: Converting JSON Array to a JSON String.

In the below example we are converting a JSON array to a string. 

<!DOCTYPE html>
<html>
<head>
    <title>Converting JSON Object to JSON String</title>
</head>
<body>
  <h3>Converting JSON Object to JSON String</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    const employeeList= [{
         "firstname": "Rick",
         "lastname": "Brown",
         "age": 22,
         "salary": 15000
        },
        {
         "firstname": "Rick",
         "lastname": "Brown",
         "age": 22,
         "salary": 15000
        }
    ];
    var string = JSON.stringify(employeeList);
    console.log(string);
    console.log(typeof string);
  </script>
</body>
</html>

Now run the above code and open the browser developer tool by pressing the F12 key and look at the Console tab where it logs the JSON string and the data type of the JSON string.

Converting JSON Object to String and String to JSON Object

When would you want to convert from JSON string to JSON object?

When receiving data from a web server, the data is always a string. Parse the data with JSON.parse() method, and the data becomes a JSON object.

Syntax:

Use the JavaScript function JSON.parse() to convert it into an object.
var jsonObj = JSON.parse(string);

Example: Converting JSON String to JSON Object

In the below example, we have a JSON string i.e. employee. We are converting that JSON string into a JSON object and printing it on the console. Notice that we are also printing the Data type of the JSON Object.

<!DOCTYPE html>
<html>
<head>
    <title>Converting JSON String to JSON Object</title>
</head>
<body>
  <h3>Converting JSON String to JSON Object</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
     var employee= '{"firstname": "Rick", "lastname": "Brown", "age": 22, "salary": 15000}';
     var object = JSON.parse(employee);
     console.log(object);
     console.log(typeof object);
  </script>
</body>
</html>

Now run the above code and open the browser developer tool by pressing the F12 key and look at the Console tab where it logs the JSON object and the data type of the JSON object as shown in the below image.

How to Convert JSON Object to String and String to JSON Object with Examples

We can also print the properties and values of the object by using the jQuery each() function. For better understanding, please have a look at the below example.

<!DOCTYPE html>
<html>
<head>
    <title>Converting JSON String to JSON Object</title>
</head>
<body>
  <h3>Converting JSON String to JSON Object</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
      const employee= '{"firstname": "Rick", "lastname": "Brown", "age": 22, "salary": 15000}';
      var object = JSON.parse(employee);
      $.each(object, function(prop,val){
         console.log(` ${prop}  :  ${val}`)
      });
  </script>
</body>
</html>

Now run the above code and open the browser developer tool by pressing the F12 key and you should get the following output in the Console tab.

Converting JSON String to JSON Object

Parsing Functions in jQuery:

We have learned in the previous article that Functions are not allowed in JSON. If you need to include a function, you have to write it as a string. You can convert it back into a function by eval() method later. For better understanding, please have a look at the below example.

<!DOCTYPE html>
<html>
<head>
    <title>Parsing Functions in jQuery</title>
</head>
<body>
  <h3>Parsing Functions in jQuery</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
      const employee = '{"firstname": "Rick", "lastname": "Brown", "age": "function() { return 22; }", "salary": 15000}';
      let object = JSON.parse(employee);
      object.age = eval(`(${object.age})`);
      console.log(` The age of the employee is ${object.age()}`)
  </script>
</body>
</html>

Output: The age of the employee is 22

Parsing Dates in jQuery:

We have learned from the previous article that Date objects are not allowed in JSON. If you need to include a date, you have to write it as a string. You can convert it back into a date object later. For better understanding, please have a look at the below example.

<!DOCTYPE html>
<html>
<head>
    <title>Parsing Functions in jQuery</title>
</head>
<body>
  <h3>Parsing Functions in jQuery</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
      const employee = '{"firstname": "Rick", "lastname": "Brown", "age": 22, "salary": 15000, "DOB": "1997-05-15"}';
      let object = JSON.parse(employee);
      object.DOB = new Date(object.DOB);
      console.log(`The DOB of the employee is ${object.DOB}`)
  </script>
</body>
</html>

Output: The DOB of the employee is Thu May 15 1997 05:30:00 GMT+0530 (India Standard Time)

You can also use the second parameter, of the JSON.parse() function, called reviver. The reviver parameter is a function that checks each property, before returning the value. For better understanding, please have a look at the below example.

<!DOCTYPE html>
<html>
<head>
    <title>Parsing Functions in jQuery</title>
</head>
<body>
  <h3>Parsing Functions in jQuery</h3>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
      const employee = '{"firstname": "Rick", "lastname": "Brown", "age": 22, "salary": 15000, "DOB": "1997-05-15"}';
      let object = JSON.parse(employee, function (key, value) {
         if (key == "DOB") {
            return new Date(value);
         } else {
            return value;
         }
      });
      console.log(`The DOB of the employee is ${object.DOB}`)
  </script>
</body>
</html>

In the above example, we are converting a string into a date by the reviver function. You will get the same output as the previous example.

In the next article, I am going to discuss jQuery DOM Manipulation Methods with Examples. Here, in this article, I try to explain How to Convert JSON Object to String and String to JSON Object with Examples and I hope you enjoy this Converting JSON Object to String and String to JSON Object article.

Leave a Reply

Your email address will not be published.