Skip to content
Advertisement

Convert a string to an object and call a function

I want to store an object as a string, and then convert ot back to an object and call a method of this object.

    user.delete() // this works
    self.user = JSON.stringify(user)
    const storeUser = JSON.parse(self.user)
    storeUser.delete() // Error: delete is not a function

Advertisement

Answer

If JSON.parse and JSON.stringify would allow a copy of methods, your code would be insecure and would have risks of people running arbitrary code on your server/computer since normally JSON string comes from external sources.

You should allow your User’s class to parse a json and create a new instance based on that json:

class User {
  constructor(someRandomProperty) {
    // ... code
  }

  static fromJson(json) {
    let parsedJson;
    try {
      parsedJson = JSON.parse(json);
    } catch (error) {
      throw new Error("Invalid Json User");
    }

    return new User(parsedJson.someRandomProperty);
  }

  delete() {
    // .... code
  }
}

And then you would copy the user like this:

User.fromJson(yourJsonStrinHere)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement