B
B
b4rret2015-12-15 23:49:17
JavaScript
b4rret, 2015-12-15 23:49:17

How to preserve the type of an object in JavaScript after JSON conversions?

Sorry for the noob question, I'm just starting to learn JS.
I have the following constructor

function User(id, name) {
  this.id = id;
  this.name = name;
}

Further
var user = new User(1, 'Вася');

var json = JSON.stringify(user);
var user2 = JSON.parse(json);

console.log(user2 instanseof User); // false

How to make it return true?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2015-12-16
@b4rret

There is no such mechanism. You can use something like this (working example https://jsfiddle.net/83bun7xt/ ):

function serialize(entity) {
    return JSON.stringify({ type: entity.constructor.name, data: entity });
}

function deserialize(str, types) {
    var parsed = JSON.parse(str);
    return types[parsed.type] ? new types[parsed.type](parsed.data) : {};
}

function User(data) {
  this.id = data.id;
  this.name = data.name;
}

var user = new User({ id: 1, name: 'Nik' });
console.log('User ->', user, ' instanceOf User ===', user instanceof User);
// User -> User {id: 1, name: "Nik"}  instanceOf User === true

var userJSON = serialize(user);
console.log('Serialized user ->', userJSON);
// Serialized user -> {"type":"User","data":{"id":1,"name":"Nik"}}

var restoredUser = deserialize(userJSON, { 'User': User });
console.log('Deserialized user ->', restoredUser, ' instanceOf User ===', restoredUser instanceof User);
// Deserialized user -> User {id: 1, name: "Nik"}  instanceOf User === true

//

D
Dark_Scorpion, 2015-12-16
@Dark_Scorpion

There is no such mechanism, because objects are compared, but they are different! But you can compare, not by reference, but by content, i.e. compare json strings or run through the fields comparing their values.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question