Python中json.load()和json.loads()有哪些區別

一、圖解

json.loads():解析一個有效的JSON字符串並將其轉換為Python字典
json.load():從一個文件讀取JSON類型的數據,然後轉轉換成Python字典

二、json.loads()用法

1、例子

import json

data = {
"name": "Satyam kumar",
"place": "patna",
"skills": [
"Raspberry pi",
"Machine Learning",
"Web Development"
],
"email": "[email protected]",
"projects": [
"Python Data Mining",
"Python Data Science"
]
}
with open("data_file.json", "w") as write:
json.dump(data, write)

with open("data_file.json", "r") as read_content:
print(json.load(read_content))

2、Python和Json數據類型的映射

JSON Equivalent Python
object dict
array list
string str
number int
true True
false False
null None

三、json.load()用法

import json

# JSON string:
# Multi-line string
data = """{
"Name": "Jennifer Smith",
"Contact Number": 7867567898,
"Email": "[email protected]",
"Hobbies":["Reading", "Sketching", "Horse Riding"]
}"""

# parse data:
res = json.loads(data)

# the result is a Python dictionary:
print(res)

四、此外還有一種json.dumps

json.dumps 用於將 Python 對象編碼成 JSON 字符串。

語法

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)

實例

以下實例將數組編碼為 JSON 格式數據:

#!/usr/bin/python
import json

data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]

data2 = json.dumps(data)
print(data2)

以上代碼執行結果為:

[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}]

使用參數讓 JSON 數據格式化輸出:

#!/usr/bin/python
import json

data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]

data2 = json.dumps({'a': 'Runoob', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': '))
print(data2)

以上代碼執行結果為:

{
    "a": "Runoob",
    "b": 7
}

以上就是Python中json.load()和json.loads()有哪些區別的詳細內容,更多關於Python中json.load()和json.loads()的資料請關註WalkonNet其它相關文章!

推薦閱讀: