-3

I have to build, in python, an address book of contacts using a json file. So, I have to define a class Contact which has as attributes hust the name, surname and mail. In the solution there is a function that I never would have thought of: jsonify(self). I don't understand what it does and why I need it. Someone can help me figure it out?

def jsonify(self):
    contact = {'name':self.name,'surname':self.surname,'mail':self.mail}
    return contact
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
RadioTune
  • 21
  • 5

1 Answers1

0

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.

n00dle
  • 5,949
  • 2
  • 35
  • 48
  • Your answer has been really helpful and it's very clear to a beginner like me. Thank you! So should I use this kind of function whenever I need to work with json files that "contains" classes? – RadioTune Feb 09 '20 at 13:32
  • No problem. Yes, if you have an object, which is from a custom class, and you want to store it into a JSON file, you'll need either something like this, or ideally, something like the `JSONEncoder` example I linked above. The advantage of the latter is that it's a lot more flexible than manually crafting a dictionary, but I suspect your professor gave you this example as it's easier to follow. – n00dle Feb 09 '20 at 13:43