Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

python: read json and loop dictionary

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'}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...