- 追加された行はこの色です。
- 削除された行はこの色です。
#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へ変換できます。。
----
この記事は
#vote(おもしろかった,そうでもない)
#comment
#topicpath
SIZE(10){現在のアクセス:&counter;}