Open HannulaTero opened 11 months ago
Given the parallel with JavaScript, and the web target, toJSON()
is an alternative that JavaScript uses so that might be a good choice.
on this I'd love to see some kind of deserializer type thing for constructors that tries to do the opposite given JSON without writing heaps of boilerplate to do that safely
on this I'd love to see some kind of deserializer type thing for constructors that tries to do the opposite given JSON without writing heaps of boilerplate to do that safely
The latest beta introduced optional JSON filters for both parsing and stringifying, and Alice already made Utility-functions, which basically does "toJson" behaviour and back. Forum post
Is your feature request related to a problem?
When I am making JSON-string from structs, many times I don't need all things struct has to be included in json. To avoid this, I need manually create another structure, which is then explicitly made into json. For simple struct this can be easy, but when there are nested structs, the problem becomes harder.
Describe the solution you'd like
In short,
toJson()
makes target struct provide another structure to be stringified into json instead of itself.I propose struct
toJson()
method, which is triggered when struct is being made into JSON-string byjson_stringify(struct);
This should work similar 'toString()', the idea being that instead of default action, it will return something else instead.Let's take a example what I mean.
In the example we have several different kind of variables, holding different things. Now in the example we try print foo-struct as it is. Without
toString
, it would stringify and print all information. Now with toString, we return some other string to represent foo. In this case content of name.Normally
json_stringify(...)
will make all contents of the struct into JSON-string from it, and toString or toValue doesn't affect it. Now my proposed toJson would behave similar to toString or toValue. Instead of using struct itself, toJson will provides another structure, which is then used for actual json-stringifying instead.Describe alternatives you've considered
No response
Additional context
No response