Arun
Arun

Reputation: 1220

Python : Getting values of key from JSON

Wrote a python script to collect the response header of a list of websites.Now,I have json file which has the response header of website. 1 is the ID (key) and rest all values are the response header parsed for a particular URL.

 {
    "1": {
        "transfer-encoding": "chunked", 
        "set-cookie": "lng=hi; path=/; expires=Tue, 14-Feb-2017 08:54:15 GMT; domain=.ucoz.net;, uSID=HYv2D8GG3nmptnLPRZbxuxBHi5awMLA8pwrSRf2aE8t0l9%3BEeTKJkgoo; path=/; domain=www.ucoz.net;", 
        "keep-alive": "timeout=15", 
        "server": "nginx/1.8.0", 
        "connection": "keep-alive", 
        "date": "Mon, 15 Feb 2016 08:54:15 GMT", 
        "content-type": "text/html; charset=UTF-8"
    }
}

How to get the value of server for key 1

Result :

1,nginx/1.8.0

Upvotes: 0

Views: 150

Answers (2)

Adem Öztaş
Adem Öztaş

Reputation: 21446

json.loads: Deserialize data (instance containing a JSON) to a Python object.

>>> import json
>>> data = ''' {
...     "1": {
...         "transfer-encoding": "chunked", 
...         "set-cookie": "lng=hi; path=/; expires=Tue, 14-Feb-2017 08:54:15 GMT; domain=.ucoz.net;, uSID=HYv2D8GG3nmptnLPRZbxuxBHi5awMLA8pwrSRf2aE8t0l9%3BEeTKJkgoo; path=/; domain=www.ucoz.net;", 
...         "keep-alive": "timeout=15", 
...         "server": "nginx/1.8.0", 
...         "connection": "keep-alive", 
...         "date": "Mon, 15 Feb 2016 08:54:15 GMT", 
...         "content-type": "text/html; charset=UTF-8"
...     }
... }'''
>>> d = json.loads(data)
>>> d['1']['server']
u'nginx/1.8.0'

Upvotes: 3

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

Use JSON encoder to parse data in your file:

import json
from pprint import pprint

with open('json_data.json') as json_data:    
    data = json.load(json_data)

pprint(data)
# now you can traverse your data dict....
print(data['1']['server'])

Upvotes: 3

Related Questions