Python modify json file (including Chinese)

1 Read before write (python27)

#!/usr/bin/python
import json
with open("replayScript.json", "r",encoding='utf-8') as jsonFile:
    data = json.load(jsonFile)

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

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

2 Read and write move the file location pointer together (python27)

with open("replayScript.json", "r+",encoding='utf-8') as jsonFile:
    data = json.load(jsonFile)

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

    jsonFile.seek(0)  # rewind
    json.dump(data, jsonFile,ensure_ascii=False)
    jsonFile.truncate()

3 Array type read and write

Remove the last element of jsonarray

#!/usr/bin/python
import json

with open("./config/patchconfig/patch_log.json", 'r+',encoding='utf-8') as f:
    log = json.load(f)
    log.pop(len(log) - 1)
    f.seek(0)
    json.dump(log, f,ensure_ascii=False)
    f.truncate()

 

Guess you like

Origin www.cnblogs.com/wolbo/p/12703318.html