If you want to iterate over both keys and values of the dictionary, do this:
for key, value in data.items():
print(key, value)
Answer from Lior on Stack OverflowVideos
If you want to iterate over both keys and values of the dictionary, do this:
for key, value in data.items():
print(key, value)
What error is it giving you?
If you do exactly this:
data = json.loads('{"lat":444, "lon":555}')
Then:
data['lat']
SHOULD NOT give you any error at all.
UPDATE
With Python3, you can do it in one line, using SimpleNamespace and object_hook:
import json
from types import SimpleNamespace
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))
# Or, in Python 3.13+:
# json.loads(data, object_hook=SimpleNamespace)
print(x.name, x.hometown.name, x.hometown.id)
OLD ANSWER (Python2)
In Python2, you can do it in one line, using namedtuple and object_hook (but it's very slow with many nested objects):
import json
from collections import namedtuple
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
print x.name, x.hometown.name, x.hometown.id
or, to reuse this easily:
def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values())
def json2obj(data): return json.loads(data, object_hook=_json_object_hook)
x = json2obj(data)
If you want it to handle keys that aren't good attribute names, check out namedtuple's rename parameter.
You could try this:
class User():
def __init__(self, name, username):
self.name = name
self.username = username
import json
j = json.loads(your_json)
u = User(**j)
Just create a new object and pass the parameters as a map.
You can have a JSON with objects too:
import json
class Address():
def __init__(self, street, number):
self.street = street
self.number = number
def __str__(self):
return "{0} {1}".format(self.street, self.number)
class User():
def __init__(self, name, address):
self.name = name
self.address = Address(**address)
def __str__(self):
return "{0} ,{1}".format(self.name, self.address)
if __name__ == '__main__':
js = '''{"name":"Cristian", "address":{"street":"Sesame","number":122}}'''
j = json.loads(js)
print(j)
u = User(**j)
print(u)
Use json.loads it will convert the json string to a dict containing dicts, list, etc.
Edit 2:
You can access each item like this: json_object['scans']['TotalDefense']['version']
contd.
But you may also need to json.loads(json.load(response)) as I mentioned in my comment below.
Edit 1:
In your example, we should not be seeing "scans" again for print json_object['scans'].
From http://docs.python.org/library/json.html:
>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
That page also has info on how to do more complex decoding.
import json
import urllib
import urllib2
url = "https://www.virustotal.com/vtapi/v2/file/report"
parameters = {"resource": "2aa837802b1c7867a65067525a843566029bd97e3ce99f6eb55217e219043ae1",
"apikey": "12312312312312312"}
data = urllib.urlencode(parameters)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
json_object = response.read()
print '\n '
response_dict = json.loads(json_object)
print response_dict.get("response_code",{})
This outputs the response_code's value in the object. To go with nested values, a response_dict.get("scans",{}).get("AVG",{})
could be done. THANK YOU EVERYONE!
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']
What you get from the url is a json string. And your can't parse it with index directly.
You should convert it to a dict by json.loads and then you can parse it with index.
Instead of using .read() to intermediately save it to memory and then read it to json, allow json to load it directly from the file:
wjdata = json.load(urllib2.urlopen('url'))
Here's an alternative solution using requests:
import requests
wjdata = requests.get('url').json()
print wjdata['data']['current_condition'][0]['temp_C']
Very simple:
import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print(data['two']) # or `print data['two']` in Python 2
For URL or file, use json.load(). For string with .json content, use json.loads().
#! /usr/bin/python
import json
# from pprint import pprint
json_file = 'my_cube.json'
cube = '1'
with open(json_file) as json_data:
data = json.load(json_data)
# pprint(data)
print "Dimension: ", data['cubes'][cube]['dim']
print "Measures: ", data['cubes'][cube]['meas']
I have never done this in python before but I'm pretty sure I could turn the retrieved JSON into a dictionary, but what is the best practice to convert the retrieved JSON into a class with its properties being items from the JSON.
So for example
{
"name":"Harry",
"job":"Mechanic"
}would yield
class Person:
def __init__(self, name, job):
self.name = name
self.job = jobAlso is there an easier way to do this.. something like a factory constructor.. ?