Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do JSON.stringify() and JSON.parse() change data type?

👋 I need a little bit of help to understand JSON better.

When I stringify an array with class objects then parse it back, it looks like the array loses the class instance. Can I keep the class even after parse JSON data, and if can, how? And why does this happen?

Here is the code:

class Account {
    constructor(site, login, pass) {
        this.site = site,
        this.login = login
        this.pass = pass
    }
}
const accounts = [
    new Account("website1.com", "[email protected]", "12345"),
    new Account("website2.com", "[email protected]", "23456")
]
console.log('BEFORE', accounts)


const string = JSON.stringify(accounts)
console.log(string)


const parseString = JSON.parse(string)
console.log('AFTER', parseString)

The console shows like this:

BEFORE (2) [Account, Account]
{string: "[{"site":"website1.com","login":"[email protected]"….com","login":"[email protected]","pass":"23456"}]"}
AFTER (2) [{…}, {…}]

To make things clear, is it possible to have [Account, Account] after JSON.parse()`?

Let me know if my explanation is not clear. Thank you so much!

like image 362
misakimichy Avatar asked May 11 '26 23:05

misakimichy


1 Answers

JSON has no support for types other than object, array, null, string, number and boolean.

If you kind of know what you can expect in your JSON, you can use a reviver function during parsing. For your example, this suffices:

JSON.parse(string, (k, v) => v.hasOwnProperty('site')
                             ? new Account(v.site, v.login, v.pass)
                             : v);
like image 174
Amadan Avatar answered May 14 '26 12:05

Amadan