Pages - Menu

2020年7月7日 星期二

[PYTHON]Json解析

前言

最近在搞自動購買的東西,
然後就扯到json了,
後來發現我沒有對json做一個懶人程式碼包。



正文

主要程式碼,
下面輸出可以看到型態上的差別,如果是dict的型態可以使用欄位來指定
不然就只能用數字來取值。


import json
data = [{ "a" : 1, "b" :2, "c" : 3, "d" : 4,"e" : 5 }]
jsonData =  '{ "a" : 1, "b" : 2, "c" :3, "d" : 4,"e" : 5 ,"English":{"a":"10"}}'
#將python的字串轉成json字串
jData=json.dumps(data)
print(f"the type is  {type(jData)},the data is {jData}")
#將已編碼的json字串解碼成python對象
loadJson = json.loads(jData)
print(f"the type is  {type(loadJson)},the jData is {loadJson[0]}")

#讀取json欄位
loadJson = json.loads(jsonData)
print(f"the type is  {type(loadJson)},the jData is {loadJson}")
print("specific column is " + str(loadJson['b']))
print(loadJson['English']['a'])



the type is  <class 'str'>,the data is [{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}]
the type is  <class 'list'>,the jData is {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
the type is  <class 'dict'>,the jData is {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'English': {'a': '10'}}
specific column is 2
10



ref.
python中如何判斷一個變量的數據類型?(原創)
Python Parse JSON array
[Python]如何剖析JSON資料,如何剖析JSON Array
Python JSON

沒有留言:

張貼留言