简体   繁体   中英

Update specific value in JSON file with python

I Have problem with update my JSON file form python script. My JSON file":

{"domains": 
    [
        {"name": "example1.com", "type": "mail", "category": "good", "count": 0}, 
        {"name": "example1.com", "type": "mail", "category": "bad"}, 
        {"name": "exampless.com", "type": "mail", "category": "good", "count": 13}
    ]
}

I try update "count", but only where "name" is specific

I try this code:

def redJSONlist(filename)
    with open(filename) as f:
        data = json.load(f)
    return data

def updateJSONdata(data, filename)
    filename.seek(0)
    json.dump(data, filename)
    filename.truncate()

l = redJSONlist("data.json")
for i in l['domains']:
    if(i['name'] == "exampless.com"):
        ile = i['count']
        i['count'] = ile + 1
        updateJSONdata(l, "data.json")

I got error: AttributeError: 'str' object has no attribute 'seek'

.seek and .write are methods of a file object, but you are trying to call them on the string type, which results in an error.

What are you trying to achieve by .seek(0)? - if it's to set the file reading on the first byte, it is not needed, python does it automatically on opening

You are probably searching for something like this:

data = {"abc" : "efg"}
filename = "data.json"
with open(filename) as file:
  file.write(data)
  print(type(file))
  print(type(filename))

the prints will help you understand the difference between file and filename types

Your code has a few problems:

  1. You lack a colon : at the end of your function definitions: def updateJSONdata(data, filename)

  2. The filename variable is of string type, but you try to call .seek(0) on it, which is a method for files. What you need to actually do in the updateJSONdata function is to open the file with the given filename , run json.dump and close it. The following snippet should works:

def updateJSONdata(data, filename):
    with open(filename, "w") as file: # the "w" option opens the file in write mode
        json.dump(data, file)

Note that the with block will do the resource cleanup (file closing) for you.

I have include a resource in Python file handling for you to further refer: Python file handling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM