Home > Back-end >  Update specific value in JSON file with python
Update specific value in JSON file with python

Time:07-02

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'

CodePudding user response:

.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

CodePudding user response:

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

  • Related