** 文字列からPython Object,ファイルからPython Object [#n6c6bf61]

*** 文字列からPython Object [#m8f3c650]

 import json
 
 def json_test():
   # 文字列から、Python Ojbectは、json.loads
   jsonStr = '''
 [
     {
         "company": "都営地下鉄",
         "lastupdate_gmt": 1479472082,
         "name": "浅草線",
         "source": "鉄道com RSS"
     },
     {
         "company": "京急電鉄",
         "lastupdate_gmt": 1479471904,
         "name": "京急線",
         "source": "鉄道com RSS"
     }
 ]
 '''
   data = json.loads(jsonStr)
   print_json(data)


*** ファイルから Python Ojbect [#tbaedf40]
   # ファイルから、Python Ojbect は、json.load
   filePath = "/tmp/delay.json"
   with open(filePath) as data_file:
     results = json.load(data_file)
 
   print_json(results)


** Python Ojbectを JSON文字列化する(上記の逆) [#ybabf4ab]
   # Python Object をJSON化する (上記の逆)
   resultsJSON = json.dumps(results, ensure_ascii=False)
   # resultsJSON = json.dumps(results, ensure_ascii=False, indent=4, sort_keys=True, separators=(',', ': '))
 
   print(resultsJSON) # 文字列
   print(json.loads(resultsJSON)) # もういちど、Python Object へも戻せる
 
 
 def print_json(results):
   print('-----')
   for element in results :
     print(element['company'],element['name'])
   print('-----')



** Objectっぽく操作。 [#ge61ae73]

 objListJSON = json.dumps(createList(), ensure_ascii=False)
 print(objListJSON)
 
 
 def createList():
   objList = []
   objList.append(
   {
     "company": "都営地下鉄",
     "lastupdate_gmt": 1479472082,
     "name": "浅草線",
     "source": "鉄道com RSS"
   })
   objList.append(
   {
     "company": "京急電鉄",
     "lastupdate_gmt": 1479471904,
     "name": "京急線",
     "source": "鉄道com RSS"
   })
 
   return objList


トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS