To convert any object into a JSON, we have foo.to_json
helper in ruby which returns a string. Similarly, to convert it back to its original datatype, we have to use JSON.parse(json_string)
, which does not look as good as foo.to_json
(IMHO).
So I tried to implement a helper function for that in ruby using the following code:
class String
def parse_json
JSON.parse(self)
end
end
But none of the languages I know of has such a helper method in the String class. This makes me wonder, is it a bad pattern to write code like this? The String instance should not be responsible for decoding itself into some other type of object that is present in the JSON?
Aucun commentaire:
Enregistrer un commentaire