Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: read json and loop dictionary

Tags:

I'm learning python and i loop like this the json converted to dictionary: it works but is this the correct method? Thank you :)

import json  output_file = open('output.json').read() output_json = json.loads(output_file)  for i in output_json:         print i         for k in output_json[i]:                 print k, output_json[i][k]  print output_json['webm']['audio'] print output_json['h264']['video'] print output_json['ogg'] 

here the JSON:

{     "webm":{     "video": "libvp8",     "audio": "libvorbis"     },      "h264":   {     "video": "libx264",     "audio": "libfaac"     },      "ogg":   {     "video": "libtheora",     "audio": "libvorbis"     } } 

here output:

> h264  audio libfaac video libx264  ogg > audio libvorbis video libtheora webm > audio libvorbis video libvp8 libvorbis > libx264 {u'audio': u'libvorbis', > u'video': u'libtheora'} 
like image 421
ZiTAL Avatar asked Feb 28 '11 20:02

ZiTAL


People also ask

How do I loop through a JSON file with multiple keys sub keys in Python?

Iterate through JSON with keys in Python To iterate through JSON with keys, we have to first import the JSON module and parse the JSON file using the 'load' method as shown below. It will parse the 'json_multidimensional. json' file as the dictionary 'my_dict'. Now to iterate with keys, see the below code.

How do you access a JSON string in Python?

It's pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.


1 Answers

That seems generally fine.

There's no need to first read the file, then use loads. You can just use load directly.

output_json = json.load(open('/tmp/output.json')) 

Using i and k isn't correct for this. They should generally be used only for an integer loop counter. In this case they're keys, so something more appropriate would be better. Perhaps rename i as container and k as stream? Something that communicate more information will be easier to read and maintain.

You can use output_json.iteritems() to iterate over both the key and the value at the same time.

for majorkey, subdict in output_json.iteritems():     print majorkey     for subkey, value in subdict.iteritems():             print subkey, value 

Note that, when using Python 3, you will need to use items() instead of iteritems(), as it has been renamed.

like image 156
chmullig Avatar answered Oct 12 '22 21:10

chmullig