Working with JSON in python.
What is json?
Json stands for Javascript object notation. Basically json are ways of writing javascript objects. This way of writing javascript objects have become better way of exchanging data between different languages. Understanding json is a must to know thing in this century. Its crucial that you atleast get the basic idea of what JSON is even if you dont want to know javascript as you will come across it in different languages.
Working with json in python.
Python has a dedicated module for working with JSON data. The module support converting json objects to python objects(dictionaries) also it support convertion of json string into python objects.
Convert json data into python object.
To convert JSON data into python object the loads() function of json module is used. Consider the example bellow.
import json
#The json data
json_data = '{"email":"clesta","phone":"+255879898"}'
#convert into python object(dictionary)
py_object = json.loads(json_data)
#using python object, as all data are converted into python object.
print(py_object['email'])
Python object into json object.
Conversion from python object into json object is also supported by the json module. The purpose is to get the python data into json inorder for exchange. All python object can be converted into json objects.
To convert python object into json the dumps() method of json module is used.
#Example showing how to convert python objects into json.
#python boolean
json_content = json.dumps(True)
print(json_content)
#python None type
json_content = json.dumps(None)
print(json_content)
#python list
json_content = json.dumps(["one","two"])
print(json_content)
#python dictionary.
json_content = json.dumps({"user":"clesta","email":"clessylove@example.com"})
print(json_content)
Sky is the limit. Any complex python object can be converted into json data for exchange. The same applies for the JSON data, Any json data can be converted into python object.
json.loads and json.dumps can do the process of converting JSON into python object and Python object into JSON data.
Knowing how to use json.loads and json.dumps can be enough in most cases. and perhaps is all you need to know for now. if you want to learn more about json and python please stay attached as this article will be updated weekly.
Conclussion:
Understanding JSON is a a must thing in programming. knowing how to work with json in python will help you exchange data between different languages and applications. Please dont forget to like subscribe and follow @bongobinary social account on twiter, facebook, instagram and youtube.