json的四大函式介紹(json資料和python資料之間的轉換)
阿新 • • 發佈:2018-12-08
json的四大函式介紹
在我們進行後端開發和爬蟲開發的時候,常會遇到json
資料和python
資料的轉換
, 而這些轉換雖然簡單,但是卻很容易讓人產生混淆和困惑, 接下來我將對json資料和python資料格式的轉換做一個小的介紹,希望對各位讀者能夠起到一定的幫助…
- 1.loads : json字串 --> python資料
import json
# json字串需要使用雙引號,且字串中的字典資料最有一位不能使用逗號','
# 1.loads json字串 --> python資料
json_string = """
{
"a":"hello",
"b":"hi"
}
"""
result = json.loads(json_string)
print(result, type(result))
- 結果
{'a': 'hello', 'b': 'hi'} <class 'dict'>
- 2.dumps : python資料 --> json字串
import json
# 2.dumps python資料 --> json字串
data = {
"a": "hello",
"b": "hi",
}
result = json.dumps(data)
print(result, type (result))
- 結果
{"a": "hello", "b": "hi"} <class 'str'>
- 3.load : json檔案 --> python資料
import json
# 3.load json檔案 --> python資料
with open('json.json', 'r', encoding='utf-8') as f:
# 第一種方式loads
# json_string = f.read()
# result = json.loads(json_string)
# print(result, type(result))
# 第二種方式 load
result = json.load(f)
print(result, type(result))
- json檔案
- 結果
{'a': 'hello', 'b': 'hi', 'c': '中國'} <class 'dict'>
- 4.dump : python資料 --> json檔案
import json
# 4.dump python資料 --> json檔案
data = {
"a": "hello",
"b": "hi",
"c": "中國"
}
with open('data_out.json' , 'w', encoding='utf-8') as f:
# 第一種方式dumps
# json_string = json.dumps(data)
# f.write(json_string)
# 第二種方式dump
# ensure_ascii = False 設定輸出的json檔案的中文可以顯示(可選引數)
# indent設定縮排空格的數量(使輸出的json檔案格式化, 可選引數)
json.dump(data, f, ensure_ascii=False, indent=2)
- 結果