目的
PythonでJSON形式のデータを読み取る処理の一例を記す。
読み取るJSONデータ
.json
{
"lunches" : [
{
"drink": "Green Tea",
"dessert": "Vanilla Icecream",
"foods": [
{
"name": "Rice",
"item": []
},
{
"name" : "Curry",
"item" : ["Chiken", "Onion", "Carrot"]
},
{
"name": "Omelette",
"item": ["Egg", "Butter", "Cheese"]
}
]
},
{
"drink": "Ice Coffee",
"dessert": "Chocolate Cake",
"foods": [
{
"name": "Bread",
"item": []
},
{
"name": "Bamburger",
"item": ["Beef", "Onion", "Egg"]
},
{
"name": "Salad",
"item": ["Lettuce", "Cucumber", "Tomato"]
}
]
}
]
}
実行結果
-----
Green Tea
Vanilla Icecream
Rice
Curry
Chiken
Onion
Carrot
Omelette
Egg
Butter
Cheese
-----
Ice Coffee
Chocolate Cake
Bread
Bamburger
Beef
Onion
Egg
Salad
Lettuce
Cucumber
Tomato
処理するPythonソースコード
.py
import sys
import json
import collections
def main(args):
menu_file = args[1]
menu = getMenu(menu_file)
def getMenu(menu_file=''):
'''
ファイル名を受け取りJSONオブジェクトを返す
エラー発生時はNone返す
Parameters
----------
menu_file : string
メニューファイル名
Returns
-------
menu : Any
メニュー
'''
try:
with open(menu_file, 'r') as food:
try:
decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict)
menu = decoder.decode(food.read())
except json.JSONDecodeError as e:
print('catch error : ', e)
except FileNotFoundError as e:
print('catch error : ', e)
except IOError as e:
print('catch error : ', e)
try:
for lunch in menu['lunches']:
print('-----')
print(lunch['drink'])
print(lunch['dessert'])
for food in lunch['foods']:
print(food['name'])
for food_item in food['item']:
print(' ', food_item)
except KeyError as e:
menu = None
print('catch error : ', e)
except TypeError as e:
menu = None
print('catch error : ', e)
return menu
if __name__ == "__main__":
main(sys.argv)