如何用python更新json文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13949637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update json file with python
提问by Igal
I'm trying to update existing Json file, but from some reason, the requested value is not being changed but the entire set of values (with the new value) is being appended to the original file
我正在尝试更新现有的 Json 文件,但由于某种原因,请求的值没有被更改,而是整个值集(带有新值)被附加到原始文件中
jsonFile = open("replayScript.json", "r+")
data = json.load(jsonFile)
tmp = data["location"]
data["location"] = "NewPath"
jsonFile.write(json.dumps(data))
and the result is : Required:
结果是: 必需:
{
"location": "NewPath",
"Id": "0",
"resultDir": "",
"resultFile": "",
"mode": "replay",
"className": "",
"method": "METHOD"
}
Actual:
实际的:
{
"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": ""
}
回答by Igal
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()
回答by Shawn Chin
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)
tmp = data["location"]
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.
或者,您可以使用seek()将光标移回文件开头然后开始写入,然后使用 atruncate()来处理新数据小于先前数据的情况。
with open("replayScript.json", "r+") as jsonFile:
data = json.load(jsonFile)
tmp = data["location"]
data["location"] = "NewPath"
jsonFile.seek(0) # rewind
json.dump(data, jsonFile)
jsonFile.truncate()

