0
JSON(Java Script Object Notification) is another data type apart from XML and YAML ,It’s easy for human and machine to understand than XML.
As usual, lets start with json example:
anurudh@anurudh:~/newfolder$ cat ex1_js.json
{
"hostname": "Router1",
"vendor": "cisco",
"users": {
"admin": 15,
"storage": 10
},
"vlans": [
{
"vlan_name": "VLAN10",
"vlan_id": 10
},
{
"vlan_name": "VLAN20",
"vlan_id": 20
}
]
}
We
like to put few point :
- The whole thing is wrapped in curly braces {}.
- JSON use string values when describing the keys in these constructs.
Working with JSON in Python
anurudh@anurudh:~/newfolder$ cat ex1_js.py
# Module need to be imported to use json
import json
# File is open and stored in varible dat
with open("ex1_js.json") as f:
data = f.read()
# json.loads places json data into json_out (dictionary)
json_out = json.loads(data)
# print output
print(json_out)
# Lets check the data type 'json_out'
print("The Json document loaded as type {0}\n".format(type(json_out)))
# Method json.dumps will convert python object back json string
json_out1 = json.dumps(json_out)
#print output
print(json_out1)
# Lets check the data type 'json_out1'
print("The Json document loaded as type {0}\n".format(type(json_out1)))
anurudh@anurudh:~/newfolder$
OUTPUT
anurudh@anurudh:~/newfolder$ python3 ex1_js.py
{'hostname': 'Router1', Continue reading