Improved json serialization / deserialization
This PR addresses this issue albeit in a slightly different way than was described. Instead of implementing toObject and fromObject I opted to instead:
- Implement the
fromObjectfunction (which I'm callingfromJSONsince I think that makes its purpose more obvious) - Altered the existing
toJSONmethods on each node type to deeply serialize to JSON. - Altered the existing
fromJSONmethods on each node type to deeply deserialize from JSON
Note I'd be happy to add a generic toJSON function as well but I honestly am not sure I see the value when you can always just call node.toJSON(), but maybe I'm missing something
- Altered the existing
toJSONmethods on each node type to deeply serialize to JSON.- Altered the existing
fromJSONmethods on each node type to deeply deserialize from JSON
Note @josdejong I wasn't sure if there was a reason these methods didn't work "deeply" before, but it seems to me like they would be most useful this way no?
Thanks Matt for picking this up 👍
The reason that there is no recursive implementation of .toJSON() is that this is handled by JSON.stringify already. The docs explain how to use it:
Docs: https://mathjs.org/docs/core/serialization.html
So right now, JSON.stringify (and math.replacer) is your generic toJSON function :). I think we can do the same for the new functions fromObject and toObject, so let them handle the iteration and call the fromJSON and toJSON methods. What do you think?
I think if you use JSON.stringify and let the toJSON methods to do the iteration themselves too, it will iterate twice, which is bad for performance.