25

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'}

2 Answers 2

43

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I'm getting AttributeError: 'list' object has no attribute 'iteritems'
That suggests your JSON file doesn't contain a dictionary but instead a list. Perhaps it's a list of 1 dictionary? Try printing it out and seeing exactly what it contains.
@OivaEskola the iteritems() method has been renamed to items() in Python 3, so that might be the issue.
@LaurentVanWinckel it works for me, even in Django template, thanks :D
@OivaEskola use .items().
-4

json_data = json.loads(url)

If list is there, then iterate:

 for majorkey, subdict in json_data.iteritems():
   for one_majorkey in subdict:
    for subkey, value in one_majorkey.iteritems():
        for each_subkey, valu_U in value.iteritems():
            for each_sub_subkey, value_Q in valu_U.iteritems():
                for each_sub_sub_subkey, value_num in value_Q.iteritems():
                    print each_sub_sub_subkey, value_num

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.