Write in json file with Python

This question already has an answer here:

  • Parsing values from a JSON file? 7 answers

  • I keep in mind 4 methods while I work with JSON objects in python.

  • json.dumps(<a python dict object>) - gives a string representation of json formed out of the python dict object
  • json.dump( <a python dict object>,<file obj>) - writes a json file in file object
  • json.loads(<a string>) - reads a json object from a string
  • json.load(<a json file>) - reads a json object from the file.
  • The next important thing to keep in mind is that json 's and dict in python are equivalent.

    So let us say, the file contents reside inside a file addThis.json . You have a already existing json object inside the file existing.json .

    The below code should be able to do the job

    import json
    
    existing = json.load(open("/tmp/existing.json","r"))
    addThis = json.load(open("/tmp/addThis.json","r"))
    
    for key in addThis.keys():
         existing[key] = addThis[key]
    
    json.dump(exist,open("/tmp/combined.json","w"),indent=4)
    

    Edit: Assuming the contents of the addThis is not in a file but is to be read from the console.

    import json
    
    existing = json.load(open("/tmp/existing.json","r"))
    
    addThis = input()
    # paste your json here.
    # addThis is now simply a string of the json content of what you to add
    
    addThis = json.loads(addThis) #converting a string to a json object.
    # keep in mind we are using loads and not load
    
    for key in addThis.keys():
         existing[key] = addThis[key]
    
    json.dump(exist,open("/tmp/combined.json","w"),indent=4)
    
    链接地址: http://www.djcxy.com/p/38050.html

    上一篇: 打开并阅读一个txt文件?

    下一篇: 用Python写入json文件