mirror of https://github.com/01-edu/public.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2.0 KiB
2.0 KiB
object_to_json
A lot of information on the web are shared in the JSON format. This exercise will be about transforming object to JSON and vice-versa.
Instructions
You just landed a new job, congrats! Your new task is to build two functions to allow new users to register to your new shiny website.
The new registration information comes as string formatted as JSON. You need to create a file registration.py
that will have the following functions inside:
create_new_user
that will receive adict
and will return a new object of the classUser
provided below. To be valid, the inputdict
must have ausername
key and aemail
key to be valid. The newUser
will have the sameusername
andemail
of the inputdict
. If the inputdict
is invalid, the default user will be returned.
class User:
username = 'user'
email = 'something@email.com'
user_to_json
that will receive aUser
and will return the object as a string in JSON format. Be aware of the Python types that can be converted to JSON!
Usage
Here is a possible test.py
to test your functions:
import create_new_user
import user_to_json
registration_0 = '{"username": "mario", "email": "mario@me.it"}'
registration_1 = '{"city": "Rome", "country": "Italy"}'
user_0 = create_new_user(registration_0)
user_1 = create_new_user(registration_1)
print(user_to_json(user_0))
print(user_to_json(user_1))
$ python3 test.py
{"username": "mario", "email": "mario@me.it"}
{}
$
Hints
- It is possible to convert an object to
dict
using the__dict__
casting.
class C:
a = 1
b = 2
my_obj = C()
my_obj_dict = my_obj.__dict__ # my_obj_dict will be a dictionary with the object my_obj values