3.5JSON
3-5.py
json形式のファイルを作る
import json
nobel_winners = [
{'category':'physics',
'name':'Albert Einstein',
'nationality':'Swiss',
'sex':'male',
'year':1921},
{'category':'physics',
'name':'Paul Dirac',
'nationality':'British',
'sex':'male',
'year':1933},
{'category':'chemistry',
'name':'Marle Curie',
'nationality':'Polish',
'sex':'female',
'year':1911}
]
with open('data/nobel_winners.json','w') as f:
json.dump(nobel_winners,f)
結果
dataフォルダにnobel_winners.jsonファイルが作成された
3-5a.py
そのファイルを読み出す
import json
with open('data/nobel_winners.json') as f:
nobel_winners = json.load(f)
print(nobel_winners)
3.5.1 日付と時刻
import datetime
import json
class JSONDateTimeEncoder(json.JSONEncoder):
def default(self,obj):
if isinstance(obj,(datetime.date,datetime.datetime)):
return obj.isoformat()
else:
return json.JSONEncoder.default(self,obj)
def dumps(obj):
return json.dumps(obj,cls=JSONDateTimeEncoder)
new_str = dumps({'time':datetime.datetime.now()})
print(new_str)
結果
from datetime import datetime
time_str = '2012/01/01 12:32:11'
dt = datetime.strptime(time_str,'%Y/%M/%D %H:%M:%S')
print(dt)
結果