溫馨提示×

python怎么處理json文件

小億
83
2023-12-26 22:31:51
欄目: 編程語言

在Python中處理JSON文件可以使用json模塊。下面是一些常見的JSON操作示例:

讀取JSON文件

import json

# 打開JSON文件
with open('data.json', 'r') as f:
    # 解析JSON數據
    data = json.load(f)

# 使用data變量訪問JSON中的數據
print(data)

寫入JSON文件

import json

# 要寫入的數據
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# 打開JSON文件
with open('data.json', 'w') as f:
    # 將數據寫入JSON文件
    json.dump(data, f)

將JSON字符串轉換為Python對象

import json

# JSON字符串
json_str = '{"name": "John", "age": 30, "city": "New York"}'

# 將JSON字符串轉換為Python對象
data = json.loads(json_str)

# 使用data變量訪問Python對象中的數據
print(data['name'])

將Python對象轉換為JSON字符串

import json

# Python對象
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# 將Python對象轉換為JSON字符串
json_str = json.dumps(data)

# 輸出JSON字符串
print(json_str)

以上示例中,json.load()用于從文件中讀取JSON數據,json.dump()用于將數據寫入JSON文件。json.loads()用于將JSON字符串轉換為Python對象,json.dumps()用于將Python對象轉換為JSON字符串。

0