Is it by design that JsonObject.to_json() returns a dict
Closed this issue · 1 comments
>>> import jsonobject
>>> class User(jsonobject.JsonObject):
... name: jsonobject.StringProperty(required=True)
...
>>> doe = User(name="John Doe")
>>> doe.to_json()
{'name': 'John Doe'}
>>> type(doe.to_json())
<class 'dict'>
Then adding this code to achieve a JSON string
>>> import json
>>> json.dumps(doe.to_json())
'{"name": "John Doe"}'
>>>
Though this would probable introduce a dependency on python built-in json library
Hi @aprivet, yeah it's by design. If you want (serialized) json, you can always run json.dumps(obj.to_json())
to get that. to_json()
returns a dict
that's guaranteed to be JSON-serializable. I realize that's not obvious from the name (you might expect .to_json()
to give you a JSON string), but we chose to follow the precedent set by some other popular libraries of calling deserialized JSON "json" as well, since the most common way to interact with JSON in python is in its deserialized form (i.e. as dicts, lists, etc.). See for example http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content, where the .json()
function returns deserialized json. I can see pros and cons of choosing this loose-but-practical naming convention, but for better or for worse that's what we decided to go with here.