我正在使用Jsonlines又名 ndjson ,并且想要使用 python 编辑单行中的单个键/值并更新文件中的行。
目前,Python 库 jsonlines和 json-lines似乎只允许您读取现有条目或写入新条目,但不能编辑现有条目。
例如,在jsonlines library中,您可以打开文件并将对象包装在 reader 或 writer 中:
import jsonlines
with jsonlines.open('input.jsonl') as reader:
for obj in reader:
...
with jsonlines.open('output.jsonl', mode='w') as writer:
writer.write(...)
假设您有以下 jsonlines 文件:
{"name":"Alice","age":24}
{"name":"Bob","age":22}
在 python 中更新字典相当容易。在这种情况下,它会是这样的:
entry = {"name":"Alice","age":24}
entry.update({"age":25})
图书馆似乎将这些台词作为字典打开。您可以从 jsonlines 库中调用更新方法:
import jsonlines
with open('names.jsonl', 'rb') as f:
for item in json_lines.reader(f):
item.update({'age':25})
print(item['age'])
这有两个问题:
- 它实际上不会更新文件......只是暂时更新字典
- 文件
names.jsonl
保持不变
- 文件
- 它将对所有条目执行此操作,而不仅仅是特定条目/行
- 这当然是因为在循环中打开
- 您可以根据 this solution 通过行号转到特定行
- 但它假设您知 Prop 体的行号
- 当您真的只想通过名字找到 Alice 并在该条目中更新她的年龄
最佳答案
试试这个代码:
import jsonlines
with jsonlines.open('input.jsonl') as reader, jsonlines.open('output.jsonl', mode='w') as writer:
for obj in reader:
if obj['name'] == 'Alice':
obj['age'] = 25
writer.write(obj)
它将把 input.jsonl
的所有行复制到 output.jsonl
并将 age
字段更改为 25
当 name
字段为 Alice
关于python - 在 jsonlines/nd json 中编辑一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55459942/