Wednesday, September 5, 2018

How to Convert Array to JSON and JSON to Array in Typescript/Javascript

Casting Array and JSON introduction

In Typescript applications Like Angular, Web layer will interact with Database. Interaction will happen via REST API. REST API is a separate application written any language which talks with Database. REST API takes input as JSON and Output JSON.

Angular applications which are based MVC pattern takes the input from View layer and store/holds them in an array of objects as a model in a Controler.
During development in Angular applications, We have many use cases as follows
Add/Update data
The user adds the data in the User interface, the controller gets the data in Array of the object as a model which we need to supply it REST API. So we need to convert this Array of objects to JSON objects
Read Data from Database

Angular application Consumes REST API data. This data is in the format of JSON format. This data needs to convert to Array of Objects to display it in the User interface. When you are dealing with Data from REST API, We will write an angular Services to manipulate data. Services are a delegation of the request between the Controller and Data layer.

This blog post covers how to convert Array to JSON and JSON to Array in typescript with examples
Before Doing conversion, Always understands Structure of JSON, apply logic as per JSON structure

typescript is an extended version of javascript. Below examples works on javascript environment also.

How to Convert Array of Objects to JSON with examples 

There are many ways You can convert Array to JSON
using the forEach method
Here are the explanation steps for code

  1. Created Array and initialize it with initial static objects where each object contains id and name values
  2. Create a temporary object using let keyword for holding data.
  3. forEach() method in the array is used to iterate the array of elements in the same order. This has a callback function which called for every element. 
  4. Using lambda expression, Loop through each element and add the element to a temporary object.
  5. Finally, JSON.stringify() method is used to convert Object to JSON string
let empArray = [{
    id: '1',
    name: 'kiran'
  },
 {
    id: '2',
    name: 'john'
  },{
    id: '3',
    name: 'Frank'
  },
];

let jsonObject = {};
empArray.forEach(item => obj[item.id] = item.name);
let json = JSON.stringify(jsonObject);
console.log(empArray);
console.log(json);
Output
0: {id: "1", name: "kiran"}
1: {id: "2", name: "john"}
2: {id: "3", name: "Frank"}
{"1":"kiran","2":"john","3":"Frank"}
Using ES6 Example 
ES6 introduced Spread Operator and Object assign method to process array.

  1. First called array map() method is call a function for every element during iteration and return a new array for each element. 
  2. This new array contains index=0 as id: "1" and index=1 as name: "kiran" 
  3. Create an Object with this values in map chain to return new array Next step deep copy the array of object to new object. 
  4. Convert this object to JSON string using JSON.stringify() method

Here is an example code
let jsonObject = Object.assign(...empArray.map(key => Object.values(key)).map(value => ({ [value[0]]: value[1] })));
let json = JSON.stringify(jsonObject);
console.log(empArray);
console.log(json);
Output is same for this code.

How to Convert JSON to Array Objects


  1. Created JSON object and Empty Array Object 
  2. using a for...in loop, Iterated each element of the JSON object.
  3. Add each element to Array using the push method
let jsonObject = {
    "1": "kiran",
    "2": "john",
    "3": "Frank"
};

var outputArray = [];
for (let element in jsonObject) {
    outputArray.push({
        id: element,
        name: jsonObject[element]
    });
}
console.log(outputArray)
Output is

0: {id: "1", name: "kiran"}
1: {id: "2", name: "john"}
2: {id: "3", name: "Frank"}

Related article


EmoticonEmoticon