|
Output:
{"age": 31, " Salary ": 25000," name ":" John "}
As you can see, JSON supports primitive types such as strings and numbers, as well as nested lists, tuples, and objects.
|
Exit :
["Welcome", "to", "GeeksforGeeks"] ["Welcome", "to", "GeeksforGeeks"] "Hi" 123 23.572 true false null
JSON serialization:
The process of encoding JSON is commonly referred to as serialization . This term refers to the conversion of data into a series of bytes (hence sequential) for storage or transmission over a network. To process the stream of data in a file, the Python JSON library uses the dump ()
function to convert Python objects to their corresponding JSON objects, making it easier to write data to files. See the following table below.
Python object | JSON object |
---|---|
dict | object |
list, tuple | array |
str | string |
int, long, float | numbers |
True | true |
False | false |
None | null |
Serialization example:
Let’s look at the above example Python object.
|
|
Here dumps ()
first takes two arguments: serializable a data object, and then the object to which it will be written (in byte format).
Deserializing JSON:
Deserializing is the opposite of serializing, that is, converting a JSON object to appropriate im Python objects. The load ()
method is used for this. If you have used Json data from another program or received it as a Json string format, then it can be easily deserialized using load ()
, which is usually used to load from a string, otherwise the root object is in the list or dict.
|
Deserialization example:
|
Encoding and decoding:
Encoding is defined as converting text or values into an encrypted form that can only be used by the desired user by decoding it. Here encoding and decoding is done for JSON format (object). Encoding is also known as serialization and decoding — deserialization. Python has a popular package for this operation. This package is known as Demjson . Follow these steps to install it.
For Windows
pip install demjson
For Ubuntu
sudo apt-get update sudo apt-get install python-demjson
Encoding : The encode ()
function is used to convert a python object to a JSON string representation. Syntax
demjson.encode (self, obj, nest_level = 0)
Code 1: Encoding using the demjson package
|
Exit :
[{"Chemistry": 70, "Math": 50, "physics": 60}]
Decode : The decode decode ()
function is used to convert a JSON object to a Python format type. Syntax
demjson.decode (self, obj)
Code 2: Decode using demjson package
|
Exit:
{’a’: 0,’ b’: 1, ’c’: 2,’ d’: 3, ’e’: 4 }
Code 3: Encoding using iterencode
|
Code 4: Encoding and decoding with using dumps ()
and loads()
|
Real world example:
Let’s take a real example of JSON implementation in python. A good source for practice is JSON_placeholder , it provides a great package of API requests that we will use in our example. Follow these simple steps to get started. Open the Python IDE or CLI and create a new script file, name it sample.py.
|
To learn more, click here