python:爬蟲爬取資料的處理之Json字串的處理(2)
阿新 • • 發佈:2018-11-17
#Json字串的處理
Json字串轉化為Python資料型別
import json JsonStr ='{"name":"sunck","age":"18","hobby":["money","power","English"],"parames":{"a":1,"b":2}}' JsonData = json.loads(JsonStr) print(JsonData) #結果:{'name': 'sunck', 'age': '18', 'hobby': ['money', 'power', 'English'], 'parames': {'a': 1, 'b': 2}}資料型別:<class 'dict'> print(JsonData["hobby"]) #結果:['money', 'power', 'English']
#把python資料型別轉化為Json型別
import json
PythonStr = {"name":"sunck","age":"18","hobby":["money","power","English"],"parames":{"a":1,"b":2}}
JsonData = json.dumps(PythonStr)
print(JsonData)
#字串型別為Str型
(2)本地Json檔案的轉換
#讀取和寫入本地的Json檔案
import json path =r"D:\pythonItem\爬蟲與Json\Json.json" #注意這裡的路徑字尾為json,如果沒有可以在根目錄下建立一個.json檔案 #把json檔案寫入到檔案中,注意這裡**寫入的Json型別為字串型** JsonStr =’{"name":"sunck","age":"18","hobby":["money","power","English"],"parames":{"a":1,"b":2}}‘ with open (path,"w") as f : data =json.dump(JsonStr,f) #從本地檔案中讀取json檔案 with open(path,"rb") as f : data = json.load(f) print(data) #讀取出來的資料型別為dict型