Spread the love

Sometimes in our application we want to convert JSON string to JSON object because the format of response is JSON string rather then JSON object, so in this tutorial i will show you to use JSON string to object and vise versa. JSON are used to communicate between client and server application.

Angular is most popular frontend framework and not only in angular even in javascript or other framework we ca land into the same problem so to convert JSON string to JSON object in angular here is the simplest solution

Convert string to json

JSON.parse is used to convert the string to json

let jsonString='[{"title":"test"}]';
let jsonObj = JSON.parse(jsonString);

Convert json object to string

JSON.stringify is used to convert the string to json

let jsonObj = [{"title":"test"}];
let jsonString = JSON.stringify(jsonString);

So as you can we have used two methods here

  1. JSON.stringify : Its used to convert object to json
  2. JSON.parse : Its used to convert string object to Object

Let’s take an example of convert JSON string to JSON object in angular

Step 1 : Create an angular app

First step is to setup an angular app using below command

ng new example-app

Step 2: Create a Component

Create a component and add json stringify and parse in component

ng g c hello-world
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css'],
})
export class HelloWorldComponent implements OnInit {
  jsonString: string = '[{"title":"test"},{"title":"test2"}]';
  jsonObj: Array<object>;
  jsonObj2: Array<object> = [{ title: 'test' }, { title: 'test2' }];
  constructor() {
    this.jsonObj = JSON.parse(this.jsonString);
    this.jsonString = JSON.stringify(this.jsonObj2);
  }

  ngOnInit() {}
}

Here we used to convet the string to object and object to string.

Step 3 : Create template and add html

Now, add simple html template with a *ngFor

<h2>JSON STRING TO OBJECT</h2>

<div *ngFor="let obj of jsonObj">
  {{ obj.title }}
</div>

<h2>JSON OBJECT TO STRING</h2>

{{ jsonString }}

Live Example and code:

Leave a Reply