1. 程式人生 > >python之 json模塊

python之 json模塊

文件 repr ads IT odi clas 輸出 load pan

  

import  json

data={
"no":1,
"name":"Runoob",
"url":"http://www.runoob.com"
}

json_str=json.dumps(data) # json.dumps() 函數對數據進行編碼,將其轉換成為json格式的數據
print("python 原始數據:",repr(data))
print("python json 數據:",json_str)
python_data=json.loads(json_str) # json.loads() 函數就是講json格式的數據解碼轉換成為python對應格式的數據

print(python_data)


輸出對應的結果:

python 原始數據: {‘no‘: 1, ‘name‘: ‘Runoob‘, ‘url‘: ‘http://www.runoob.com‘}


python json 數據: {"no": 1, "name": "Runoob", "url": "http://www.runoob.com"}


{‘no‘: 1, ‘name‘: ‘Runoob‘, ‘url‘: ‘http://www.runoob.com‘}

# 這個是 講格式化的數據寫入文件之中和讀取文件之中的數據
f=open("data.txt","w",encoding="utf-8")

f.write(json.dumps(data))
f.close()
f1=open("data.txt","r",encoding="utf-8")
f1=f1.read()
json_str1=json.loads(f1)
print("-----")
print(json_str1)

python之 json模塊