[英]Add data to json dict in python
hi im importing multiple json files嗨,我正在导入多个 json 文件
and i want to add current time to each doc of the file i tried this:我想将当前时间添加到我尝试过的文件的每个文档中:
for filename in os.listdir(directory):
if filename.endswith(".json"):
f = open(filename)
data = json.loads(f.read())
for i in range (len(data)):
print(data[i])
data[i].append({'Date':datetime.now()})
print(data[i])
i got this:( AttributeError: 'dict' object has no attribute 'append') because it's not a list我得到了这个:( AttributeError: 'dict' object has no attribute 'append') 因为它不是一个列表
Here is what data looks like (my json file content):这是数据的样子(我的 json 文件内容):
[{'trimestre': '2',
'season': 'spring'},
{'trimestre': '2',
'season': 'spring'}]
and i want it to look like我希望它看起来像
[{'date': '2021-06-02T12:18:22.694+02:00',
'trimestre': '2',
'season': 'spring'},
{'date': '2021-06-02T12:18:22.694+02:00',
'trimestre': '2',
'season': 'spring'}]
With date=current time Any help?日期=当前时间有什么帮助吗?
First, your answer: The only line you have to change is the one with the assignment.首先,您的答案:您必须更改的唯一行是有作业的行。 Like the answer above is also mentioning, the assignment has to be changed, like that:
就像上面的答案也提到了,分配必须改变,就像这样:
dictionary[key] = datetime.now()
However, JSON can't store a datetime object, which is why you will have to change the format.但是,JSON 不能存储日期时间 object,这就是您必须更改格式的原因。 I would therefore advise you to use strftime():
因此,我建议您使用 strftime():
dictionary[key] = datetime.now().strftime("%d/%m/%y")
You can change the format to the one you want.您可以将格式更改为您想要的格式。
PS: The JSON format actually uses these {} brackets for the outer one. PS:JSON 格式实际上使用这些 {} 括号作为外部括号。 You are using a list, which is not common.
您正在使用一个列表,这并不常见。
To add a key value pair to a dict this is the syntax:要将键值对添加到字典,语法如下:
adict[key] = value
unrelated to the question but its safer to use with open when handling files与问题无关,但在处理文件时使用open更安全
with open(filename) as json_file:
data = json.load(json_file)
# data contains a list of dicts
for json_dict in data:
json_dict['Date'] = datetime.now()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.