简体   繁体   English

使用 python 更新 JSON 文件中的特定值

[英]Update specific value in JSON file with python

I Have problem with update my JSON file form python script.我从 python 脚本更新我的 JSON 文件时遇到问题。 My JSON file":我的 JSON 文件”:

{"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'我收到错误: 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. .seek.write是文件 object 的方法,但您尝试在字符串类型上调用它们,这会导致错误。

What are you trying to achieve by .seek(0)?你想通过.seek(0)? - if it's to set the file reading on the first byte, it is not needed, python does it automatically on opening - 如果是在第一个字节设置文件读取,则不需要,python 在打开时自动执行

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)您缺少冒号:在 function 定义的末尾: 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. filename变量是string类型,但您尝试对其调用.seek(0) ,这是一种文件方法。 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.您在updateJSONdata function 中实际需要做的是打开具有给定文件名的filename ,运行json.dump并关闭它。 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.请注意, with块将为您执行资源清理(文件关闭)。

I have include a resource in Python file handling for you to further refer: Python file handling我在 Python 文件处理中包含一个资源供您进一步参考: Python 文件处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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