Encoding and Decoding :
Encoding is defined as converting the text or values into anencrypted form that can only be used by the desired user through decoding it.Here encoding and decoding is done for JSON (object)format. Encoding is also known as Serialization and Decoding is known as Deserialization. Python have a
popular package for this operation. This package is known as Demjson. To install it follow the steps below.
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 the python object into a JSON string representation. Syntax
demjson.encode(self, obj, nest_level=0)
Code 1: Encoding using demjson package
# storing marks of 3 subjects
var = [{"Math": 50, "physics":60, "Chemistry":70}]
print(demjson.encode(var))
output:
[{"Chemistry":70, "Math":50, "physics":60}]
Decoding: The decode()
function is
used to convert the JSON oject into python format type. Syntax
demjson.decode(self, obj)
code 2: Decoding using demjson package
var = '{"a":0, "b":1, "c":2, "d":3, "e":4}'
text = demjson.decode(var)
{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
Code 3: Encoding using iterencode package
# Other Method of Encoding
json.JSONEncoder().encode({"foo": ["bar"]})
'{"foo": ["bar"]}'
# Using iterencode(object) to encode a given object.
for i in json.JSONEncoder().iterencode(bigobject):
mysocket.write(i)
Code 4: Encoding and Decoding using dumps()
and loads()
# To encode and decode operations
import json
var = {'age':31, 'height'= 6}
x = json.dumps(var)
y = json.loads(var)
print(x)
print(y)
# when performing from a file in disk
with open("any_file.json", "r") as readit:
x = json.load(readit)
print(x)
Comments