如何用 python 更新 json 文件

我正在尝试更新现有的 Json 文件,但由于某种原因,请求的值没有被更改,而是将整个值集(带有新值)附加到原始文件

jsonFile = open("replayScript.json", "r+")
data = json.load(jsonFile)




tmp = data["location"]
data["location"] = "NewPath"


jsonFile.write(json.dumps(data))

结果就是: 要求:

{
"location": "NewPath",
"Id": "0",
"resultDir": "",
"resultFile": "",
"mode": "replay",
"className":  "",
"method":  "METHOD"
}

实际情况:

{
"location": "/home/karim/storm/project/storm/devqa/default.xml",
"Id": "0",
"resultDir": "",
"resultFile": "",
"mode": "replay",
"className":  "",
"method":  "METHOD"
}
{
"resultDir": "",
"location": "pathaaaaaaaaaaaaaaaaaaaaaaaaa",
"method": "METHOD",
"className": "",
"mode": "replay",
"Id": "0",
"resultFile": ""
}
266467 次浏览
def updateJsonFile():
jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
data = json.load(jsonFile) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file


## Working with buffered content
tmp = data["location"]
data["location"] = path
data["mode"] = "replay"


## Save our changes to JSON file
jsonFile = open("replayScript.json", "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()

The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.

The easiest solution would be to close the file after you've read it in, then reopen it for writing.

with open("replayScript.json", "r") as jsonFile:
data = json.load(jsonFile)


data["location"] = "NewPath"


with open("replayScript.json", "w") as jsonFile:
json.dump(data, jsonFile)

Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.

with open("replayScript.json", "r+") as jsonFile:
data = json.load(jsonFile)


data["location"] = "NewPath"


jsonFile.seek(0)  # rewind
json.dump(data, jsonFile)
jsonFile.truncate()
def updateJsonFile():
with open(os.path.join(src, "replayScript.json"), "r+") as jsonFile:
data = json.load(jsonFile)
jsonFile.truncate(0)
jsonFile.seek(0)
data["src"] = "NewPath"
json.dump(data, jsonFile, indent=4)
jsonFile.close()
def writeConfig(key, value):
with open('config.json') as f:
data = json.load(f)
# Check if key is in file
if key in data:
# Delete Key
del data[key]
cacheDict = dict(data)
# Update Cached Dict
cacheDict.update({key:value})
with open(dir_path + 'config.json', 'w') as f:
# Dump cached dict to json file
json.dump(cacheDict, f, indent=4)