Python修改JSON中的值

admin Python評論6261字數 551閱讀模式

以下是一個完整的示例代碼,演示如何使用Python修改JSON中的值:

import json

# 讀取JSON文件
with open('data.json', 'r') as file:
    data = json.load(file)

# 修改鍵對應的值
data['key'] = 'new value'

# 將數據寫回JSON文件
with open('data.json', 'w') as file:
    json.dump(data, file)

請注意,上述示例中的`data.json`是要修改的JSON文件名。您需要將其替換為你實際使用的JSON文件名。文章源自網吧系統(tǒng)維護-http://www.s143.cn/11005.html

如果要修改JSON字符串,可以將代碼修改如下:文章源自網吧系統(tǒng)維護-http://www.s143.cn/11005.html

import json

# 讀取JSON字符串
json_string = '{"key": "value"}'
data = json.loads(json_string)

# 修改鍵對應的值
data['key'] = 'new value'

# 將數據轉換為JSON字符串
json_string = json.dumps(data)

print(json_string)

上述示例中,我們先將JSON字符串加載為Python數據結構,然后修改鍵對應的值,并最終將修改后的數據轉換回JSON格式的字符串,并打印輸出。文章源自網吧系統(tǒng)維護-http://www.s143.cn/11005.html

相關文章:

python獲取json文件內容
AU3簡易json讀取示例文章源自網吧系統(tǒng)維護-http://www.s143.cn/11005.html 文章源自網吧系統(tǒng)維護-http://www.s143.cn/11005.html

版權聲明:文章圖片資源來源于網絡,如有侵權,請留言刪除!!!
廣告也精彩
admin
  • 本文由 發(fā)表于 2023年8月15日 17:59:51
  • 轉載請務必保留本文鏈接:http://www.s143.cn/11005.html
匿名

發(fā)表評論

匿名網友 填寫信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: