Javascript Json Convert Javascript class to Json string

Description

Javascript Json Convert Javascript class to Json string


class Person {/*  w w  w.ja v a2s  .  c  om*/
    constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.kind = "Person";
    }

    name() { return this.firstName + " " + this.lastName; }
}
var person1 = new Person("CSS", "HTML");
console.log(person1);           
json = JSON.stringify(person1);
console.log(json);             
console.log(typeof json);      

obj = JSON.parse(json);
console.log(obj);              
console.log(typeof obj);       
// Note: loss of Person type after parse()

// Note: Use resulting object to provide parameters to constructor
var person2 = new Person(obj.firstName, obj.lastName);
console.log(person2);           

// Note: Object destructuring syntax
var {firstName, lastName} = JSON.parse(json);
console.log(firstName + " " + lastName);     
var person3 = new Person(firstName, lastName);
console.log(person3);



PreviousNext

Related