#author("2018-07-22T16:25:31+00:00","default:masatomix","masatomix")
#author("2018-07-22T16:25:41+00:00","default:masatomix","masatomix")
#topicpath
----

#contents



** 文字列から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
Pythonってわりと使いやすい :-)


**HTTPの戻りJSONを取り扱う [#y8064c04]
 import json
 import requests
 
 def json_test2():
   r = requests.get('https://s3-ap-northeast-1.amazonaws.com/nu.mine.kino.temperature/delay.json')
   results = json.dumps(r.json(), ensure_ascii=False)
   print(results)

戻ってきたオブジェクトは r.json() でPython Objectへ変換できます。。

[[クイックスタート ― requests-docs-ja 1.0.4 documentation>http://requests-docs-ja.readthedocs.io/en/latest/user/quickstart/#post]]


***関連リンク [#d66c3ebc]
**関連リンク [#d66c3ebc]
-[[[Python] インスタンスのプロパティへ動的にアクセスする - YoheiM .NET>https://www.yoheim.net/blog.php?q=20161002]]


----
この記事は
#vote(おもしろかった,そうでもない)

#comment

#topicpath

SIZE(10){現在のアクセス:&counter;}

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS