0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでJSON形式のデータを読み取る

Posted at

目的

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)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?