Using the json
library, you can convert objects into JSON really easily, but it needs to know how to go about converting them. The library doesn't know how to interpret your custom class:
>>> import json
>>> contact = Contact("Hello", "World", "hello@world.com")
>>> contact_json = json.dumps(contact)
TypeError: Object of type 'Contact' is not JSON serializable
(json.dumps(obj)
converts its input to JSON and returns it as a string. You can also do json.dump(obj, file_handle)
to save it to a file).
A dictionary is a known type in Python, so the json
library knows how to convert it into json
format:
>>> import json
>>> contact = Contact("Hello", "World", "hello@world.com")
>>> contact_json = json.dumps(contact.jsonify())
{
"name": "Hello",
"surname": "World",
"mail": "hello@world.com"
}
Using that jsonify
method, you're converting the fields from your class into something that the json
library can understand and knows how to translate.
This is a quick and easy way to serialise your object into JSON, but isn't necessarily the best way to do it - ideally you'd tell the JSON library how to interpret your class (see this related question: How to make a class JSON serializable).
Edit: Seeing the comment discussion - I'm assuming here you have an understanding of Python data structures and classes. If this is not the case it's worth reading up on those first.