簡體   English   中英

Python: json 轉儲添加了額外的雙引號? 如何刪除?

[英]Python: json dump adds additional double quotes ! how to remove?

在 JSON 轉儲 python 在值中添加額外的“”之后,我正在嘗試更新 JSON 文件中的值。 我正在嘗試刪除。 你能有人幫忙嗎。

原始 JSON 文件數據

{
    "ProjectBranch": "Dev", 
    "BaselineRestore": {
        "releaseName": "02", 
        "useProcessedBaseline": false, 
        "incrementalRun": false, 
        "breakPipelinePostRestore": false, 
        "releaseYear": "2022", 
        "debugMode": true
    }
}

我的 python 腳本

import os
import glob
import json
import shutil
import re

cwd = os.getcwd()
pipeline_config_file = os.path.join(cwd, "config", "test.json")

with open(pipeline_config_file, "r+") as f:
    data = json.load(f)
    incrementalRun = str(data['BaselineRestore']['incrementalRun']).lower()
    data['BaselineRestore']['incrementalRun'] = 'true'
    data['BaselineRestore']['incrementalRun'] = data['BaselineRestore']['incrementalRun'].strip()
    #data = data.replace('"true"', 'true')

with open(pipeline_config_file, 'w') as f:
    json.dump(data, f, indent=4)

腳本 output

{
    "ProjectBranch": "Dev", 
    "BaselineRestore": {
        "releaseName": "02", 
        "useProcessedBaseline": false, 
        "incrementalRun": "true", 
        "breakPipelinePostRestore": false, 
        "releaseYear": "2022", 
        "debugMode": true
    }

預期數據

{
    "ProjectBranch": "Dev", 
    "BaselineRestore": {
        "releaseName": "02", 
        "useProcessedBaseline": false, 
        "incrementalRun": true,
        "breakPipelinePostRestore": true, 
        "releaseYear": "2022", 
        "debugMode": true
    }
}

您的行data['BaselineRestore']['incrementalRun'] = 'true' ' 在此處放置一個字符串'true' ,而不是True boolean。 這就是造成兩者差異的原因。

你應該使用:

import os
import glob
import json
import shutil
import re

cwd = os.getcwd()
pipeline_config_file = os.path.join(cwd, "config", "test.json")

with open(pipeline_config_file, "r+") as f:
    data = json.load(f)
    data['BaselineRestore']['incrementalRun'] = True

with open(pipeline_config_file, 'w') as f:
    json.dump(data, f, indent=4)

假設您的目標是專門將incrementalRunfalse更新為true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM