Dealing with JSON in Python
Lesson 3 of 10 in Coddy's Social media Search Project - Python JSON Fundamentals course.
Let's learn how to deal with a JSON string in Python
Python's built-in json package is required for dealing with json objects. Remember to import the json package to access it's features.
import jsonPython allows JSON strings to be converted as python dictionary object and vice versa. This allows us to process the data within the JSON efficiently in python.
Let's say you have a JSON string variable with you - name_json:
name_json = '{ "name": "David" }'The variable name_json is just another str type variable. However, we can see that this is indeed in JSON format.
This means, this particular kind of string can be converted to a dictionary object in python.
This conversion can be done using the loads method in the json package. Here's how we can do that:
dict_name_json = json.loads(name_json)You can convert ANY python dictionaries back into a JSON string as well - using the dumps method.
name_json = json.dumps(dict_name_json)
Challenge
EasyWrite a function get_json() that gets no input.
And returns the JSON dictionary object with the below information:
| name | city | gender |
|---|---|---|
| Aaron | Paris | Male |
Try it yourself
def get_json():
json_str = '' # << Write JSON string here
# For Example: json_str = '{"name":"Aaron"}'
# Write code here