如何将数据附加到 json 文件?
- 2025-03-14 08:57:00
- admin 原创
- 57
问题描述:
我正在尝试创建一个函数来向 json 文件添加条目。最终,我想要一个如下所示的文件
[{"name" = "name1", "url" = "url1"}, {"name" = "name2", "url" = "url2"}]
等等。这是我所拥有的:
def add(args):
with open(DATA_FILENAME, mode='r', encoding='utf-8') as feedsjson:
feeds = json.load(feedsjson)
with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump(entry, feedsjson)
这确实会创建一个条目,例如{"name"="some name", "url"="some url"}
。但是,如果我再次使用此add
功能,使用不同的名称和 URL,第一个条目将被覆盖。我需要做什么才能将第二个(第三个……)条目附加到第一个条目?
编辑:这个问题的第一个答案和评论指出了一个明显的事实,即我没有feeds
在写入块中使用。不过,我不知道该怎么做。例如,以下显然不行:
with open(DATA_FILENAME, mode='a+', encoding='utf-8') as feedsjson:
feeds = json.load(feedsjson)
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump(entry, feeds)
解决方案 1:
json 可能不是磁盘格式的最佳选择;它在附加数据方面遇到的麻烦就是一个很好的例子。具体来说,json 对象的语法意味着必须读取和解析整个对象才能理解它的任何部分。
幸运的是,还有很多其他选项。一个特别简单的选项是 CSV;它得到了 Python 标准库的良好支持。最大的缺点是它只适用于文本;如果需要,它需要程序员采取额外措施将值转换为数字或其他格式。
另一个没有此限制的选项是使用 sqlite 数据库,它在 python 中也有内置支持。这可能与您已有的代码有较大差异,但它更自然地支持您显然试图构建的“稍微修改”模型。
解决方案 2:
您可能希望使用 JSON列表而不是字典作为顶层元素。
因此,用一个空列表初始化文件:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as f:
json.dump([], f)
然后,您可以将新条目附加到此列表:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
entry = {'name': args.name, 'url': args.url}
feeds.append(entry)
json.dump(feeds, feedsjson)
请注意,执行速度会很慢,因为每次调用时都会重写文件的全部内容add
。如果您在循环中调用它,请考虑预先将所有提要添加到列表中,然后一次性将列表写出。
解决方案 3:
如果文件存在,则将条目附加到文件内容,否则将条目附加到空列表并写入文件:
a = []
if not os.path.isfile(fname):
a.append(entry)
with open(fname, mode='w') as f:
f.write(json.dumps(a, indent=2))
else:
with open(fname) as feedsjson:
feeds = json.load(feedsjson)
feeds.append(entry)
with open(fname, mode='w') as f:
f.write(json.dumps(feeds, indent=2))
解决方案 4:
使用a
而不是w
应该可以让您更新文件而不是创建新文件/覆盖现有文件中的所有内容。
请参阅此答案以了解模式的差异。
解决方案 5:
一种可能的解决方案是手动进行连接,下面是一些有用的代码:
import json
def append_to_json(_dict,path):
with open(path, 'ab+') as f:
f.seek(0,2) #Go to the end of file
if f.tell() == 0 : #Check if file is empty
f.write(json.dumps([_dict]).encode()) #If empty, write an array
else :
f.seek(-1,2)
f.truncate() #Remove the last character, open the array
f.write(' , '.encode()) #Write the separator
f.write(json.dumps(_dict).encode()) #Dump the dictionary
f.write(']'.encode()) #Close the array
在编辑脚本外部的文件时应小心,不要在末尾添加任何空格。
解决方案 6:
这对我有用:
with open('file.json', 'a') as outfile:
outfile.write(json.dumps(data))
outfile.write(",")
outfile.close()
解决方案 7:
我有一些类似的代码,但每次都不会重写整个内容。这是为了定期运行并在数组末尾附加一个 JSON 条目。
如果文件尚不存在,它会创建它并将 JSON 转储到数组中。如果文件已创建,它会转到末尾,]
用替换 并,
放入新的 JSON 对象,然后用另一个]
# Append JSON object to output file JSON array
fname = "somefile.txt"
if os.path.isfile(fname):
# File exists
with open(fname, 'a+') as outfile:
outfile.seek(-1, os.SEEK_END)
outfile.truncate()
outfile.write(',')
json.dump(data_dict, outfile)
outfile.write(']')
else:
# Create file
with open(fname, 'w') as outfile:
array = []
array.append(data_dict)
json.dump(array, outfile)
解决方案 8:
import jsonlines
object1 = {
"name": "name1",
"url": "url1"
}
object2 = {
"name": "name2",
"url": "url2"
}
# filename.jsonl is the name of the file
with jsonlines.open("filename.jsonl", "a") as writer: # for writing
writer.write(object1)
writer.write(object2)
with jsonlines.open('filename.jsonl') as reader: # for reading
for obj in reader:
print(obj)
请访问更多信息https://jsonlines.readthedocs.io/en/latest/
解决方案 9:
您永远不会写任何与您读入的数据有关的内容。您是否要将 feed 中的数据结构添加到您正在创建的新结构中?
或者也许您想以追加模式打开文件open(filename, 'a')
,然后添加字符串,通过写入而json.dumps
不是使用生成的字符串json.dump
- 但 nneonneo 指出这将是无效的 json。
解决方案 10:
您可以简单地从源文件导入数据,读取它,并保存要附加到变量的内容。然后打开目标文件,将里面的列表数据分配给一个新变量(假设这些都将是有效的 JSON),然后对此列表变量使用“append”函数并将第一个变量附加到它。Viola,您已将数据附加到 JSON 列表。现在只需用新附加的列表(作为 JSON)覆盖目标文件即可。
'open' 函数中的 'a' 模式在这里不起作用,因为它只会将所有内容附加到文件末尾,这会使其成为无效的 JSON 格式。
解决方案 11:
例如使用 json.load、json.update、json.dump 如下:
with open('data.json', mode='r') as file:
data = json.load(file)
new_record = {key: {inner_key:content}} # Whatever your structure is
data.update(new_record)
with open('data.json', mode='w') as file:
data.dump(data, file, indent=4)
解决方案 12:
假设你有以下的字典
d1 = {'a': 'apple'}
d2 = {'b': 'banana'}
d3 = {'c': 'carrot'}
您可以将其转换为如下组合 json:
master_json = str(json.dumps(d1))[:-1]+', '+str(json.dumps(d2))[1:-1]+', '+str(json.dumps(d3))[1:]
因此,附加到 json 文件的代码将如下所示:
dict_list = [d1, d2, d3]
for i, d in enumerate(d_list):
if i == 0:
#first dict
start = str(json.dumps(d))[:-1]
with open(str_file_name, mode='w') as f:
f.write(start)
else:
with open(str_file_name, mode='a') as f:
if i != (len(dict_list) - 1):
#middle dicts
mid = ','+str(json.dumps(d))[1:-1]
f.write(mid)
else:
#last dict
end = ','+str(json.dumps(d))[1:]
f.write(end)
扫码咨询,免费领取项目管理大礼包!