Parsing JSON in TypeScript

1- TypeScript JSON

 
As you know, TypeScript can be considered as an enhanced version of JavaScript. Finally, TypeScript is also converted to JavaScript code that can be executed in the browser or other JavaScript environments such as NodeJSTypeScript supports all JavaScript libraries and API documentation.
The simplest way to parse JSON data is to use JSON.parse(..) and JSON.stringify(..) methods. There is no difference in how to use them in JavaScript and TypeScript.
JSON

// Static methods:
parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
Consider using one of the JSON libraries below if you are developing a large TypeScript project.

2- JSON.parse(..)


parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
Converts a JSON text to a TypeScript object.
  • text: A JSON text.
  • reviver: An optional function called for each property of this JSON. The [key=''] parameter corresponds to the global JSON object. Leaf-level properties will be executed first, root-level properties will be executed last.
Example: Use the JSON.parse(..) method to convert a JSON text into an object.
json_parse_ex1.ts

function json_parse_ex1_test() {
    let jsonString = `  {
        "name": "John Smith",
        "email": "[email protected]",
        "contact": {
         "address": "Address 1",
         "phone": "12345"
        }
       }
    `;
    // Return an object.
    let empObj =  JSON.parse(jsonString);
    
    console.log(empObj);
    console.log(`Address: ${empObj.contact.address}`);
}
json_parse_ex1_test(); // Call the function.
Output:

{
  name: 'John Smith',
  email: '[email protected]',
  contact: { address: 'Address 1', phone: '12345' }
}
Address: Address 1
Example: Use the JSON.parse(..) method with the participation of the reviver function, to convert a JSON text into an object of a class.
json_parse_ex2.ts

class Employee {
    employeeName: string;
    employeeEmail: string;
    contact: Contact;
    constructor(employeeName: string, employeeEmail: string, contact: Contact) {
        this.employeeName = employeeName;
        this.employeeEmail = employeeEmail;
        this.contact = contact;
    }
}
class Contact {
    address: string;
    phone: string;
    constructor(address: string, phone: string) {
        this.address = address;
        this.phone = phone;
    }
}

function json_parse_ex2_test() {
    let jsonString = `  {
        "name": "John Smith",
        "email": "[email protected]",
        "contact": {
         "address": "Address 1",
         "phone": "12345"
        }
       }
    `;
    // Return an object.
    let empObj = JSON.parse(jsonString, function (key: string, value: any) {
        if(key == 'name') {
            return (value as string).toUpperCase(); // String.
        } else if (key == 'contact') {
            return new Contact(value.address, value.phone);
        } else if (key == '') { // Entire JSON
            return new Employee(value.name, value.email, value.contact);
        }
        return value;
    });
    console.log(empObj);

    console.log(`Employee Name: ${empObj.employeeName}`);
    console.log(`Employee Email: ${empObj.employeeEmail}`);
    console.log(`Phone: ${empObj.contact.phone}`);
}
json_parse_ex2_test(); // Call the function.
Output:

Employee {
  employeeName: 'JOHN SMITH',
  employeeEmail: '[email protected]',
  contact: Contact { address: 'Address 1', phone: '12345' }
}
Employee Name: JOHN SMITH
Employee Email: [email protected]
Phone: 12345

3- JSON.stringify(..) *


stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
Converts a value or object to a JSON text.
  • value: A value, usually an object or an array, to convert to JSON text.
  • replacer: An optional function, used to customize the results.
  • space: Add indents, spaces, or line break characters to JSON text to make it easier to read.
Example: Converting values to JSON text:
json_stringify_ex1a.ts

console.dir(JSON.stringify(1));
console.dir(JSON.stringify(5.9));
console.dir(JSON.stringify(true));
console.dir(JSON.stringify(false));
console.dir(JSON.stringify('falcon'));
console.dir(JSON.stringify("sky"));
console.dir(JSON.stringify(null));
Output:

'1'
'5.9'
'true'
'false'
'"falcon"'
'"sky"'
'null'
Example: Converting an object to a JSON text:
json_stringify_ex1b.ts

function json_stringify_ex1b_test() {
    // An Object:
    let emp = {
        name: 'John Smith',
        email: '[email protected]',
        contact: { address: 'Address 1', phone: '12345' }
    };
    let jsonString = JSON.stringify(emp);
    console.log(jsonString);
}
json_stringify_ex1b_test(); // Call the function.
Output:

{"name":"John Smith","email":"[email protected]","contact":{"address":"Address 1","phone":"12345"}}
Example: Using JSON.stringify(..) method with replacer parameter.
json_stringify_replacer_ex1a.ts

function json_stringify_replacer_ex1a_test() {
    // An Object:
    let emp = {
        name: 'John Smith',
        email: '[email protected]',
        contact: { address: 'Address 1', phone: '12345' }
    };
    let jsonString = JSON.stringify(emp, function (key: string, value: any) {
        if (key == 'contact') {
            return undefined;
        } else if (key == 'name') {
            return (value as string).toUpperCase();
        }
        return value;
    });
    console.log(jsonString);
}
json_stringify_replacer_ex1a_test(); // Call the function.
Output:

{"name":"JOHN SMITH","email":"[email protected]"}

4- JSON.stringify(..) **


stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
Converts a value or object to a JSON text.
  • value: A value, usually an object or an array, to convert to JSON text.
  • replacer: An optional array of strings or numbers. As a list of approved properties, they will appear in the returned JSON text.
  • space: Add indents, spaces, or line break characters to JSON text to make it easier to read.
json_stringify_replacer_ex2a.ts

function json_stringify_replacer_ex2a_test() {
    // An Object:
    let emp = {
        name: 'John Smith',
        email: '[email protected]',
        contact: { address: 'Address 1', phone: '12345' }
    };
    let replacer = ['email', 'contact', 'address'];
    let jsonString = JSON.stringify(emp, replacer, '  ');
    console.log(jsonString);
}
json_stringify_replacer_ex2a_test(); // Call the function.
Output:

{
  "email": "[email protected]",
  "contact": {
    "address": "Address 1"
  }
}