json files to dictionary python

misalkan anda mempunyai file json seperti berikut :

{
    'host':['192.168.122.250','192.168.122.251','192.168.122.253']
    'username':['vyos','vyos','vyos']
    'password':['vyos','vyos','vyos']
}

lalu buat script pythonnya :

import json

# open json and read into raw text
raw = open('inventory.json').read()

# loads the raw into loads() function to create dict
data = json.loads(raw)

# check data type
print ("\nType data :")
print (type(data))

# check the data
print ("\nAll data :")
print (data)

# print key username
print ("\nUsername key data :")
print (data["username"])

# print Spesific data
print ("\nSpesific data :")
print (data["host"][2])

berikut adalah outputnya :

zufar@zufar:~/Documents/Technology/Programming/Python/telnetlib$ python lab2.py

Type data :
<type 'dict'>

All data :
{u'username': [u'vyos', u'vyos', u'vyos'], u'host': [u'192.168.122.250', u'192.168.122.251', u'192.168.122.253'], u'password': [u'vyos', u'vyos', u'vyos']}

Username key data :
[u'vyos', u'vyos', u'vyos']

Spesific data :
192.168.122.253

ini juga berlaku untuk nested json, seperti :

{
    "RouterA": {
        "ip":"192.168.1.1",
        "username":"vyos",
        "password":"vyos"
    },
    "RouterB": {
        "ip":"192.168.1.2",
        "username":"vyos",
        "password":"vyos"
    }
}

 

Comments are closed.