How to restore original object/type from JSON?

前端 未结 6 1695
旧时难觅i
旧时难觅i 2020-12-05 19:38

Its easy to load JSON into an object in javascript using eval or JSON.parse.

But if you have a proper \"class\" like function, how do you get the JSON data into it?<

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 20:09

    Many frameworks provide an 'extend' function that will copy fields over from one object to another. You can combine this with JSON.parse to do what you want.

    newPerson = new Person();
    _.extend(newPerson, JSON.parse(aPersonJSON));
    

    If you don't want to include something like underscore you can always copy over just the extend function or write your own.

    Coffeescript example because I was bored:

    JSONExtend = (obj, json) ->
      obj[field] = value for own field, value of JSON.parse json
      return obj
    
    class Person
      toString: -> "Hi I'm #{@name} and I'm #{@age} years old."
    
    
    dude = JSONExtend new Person, '{"name":"bob", "age":27}'
    console.log dude.toString()
    

提交回复
热议问题