python - 在 jsonlines/nd json 中编辑一行

标签 python json

我正在使用Jsonlines又名 ndjson ,并且想要使用 python 编辑单行中的单个键/值并更新文件中的行。

目前,Python 库 jsonlinesjson-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 字段更改为 25name 字段为 Alice

关于python - 在 jsonlines/nd json 中编辑一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55459942/

相关文章:

python - Python 中描述符的使用示例

python - 在特定 Python 版本上安装包

c# - 在 C# 中使用 newtonsoft 查找并返回 JSON 差异?

javascript - Oracle 9i - 将 Varchar2 转换为 javascript 转义的 UTF-8?

php - 使用 jQuery/PHP/AJAX/JSON 进行 Lucene/Solr 即时开发

python - 根据上面的行创建新的数据框行

python - "eval"和 "int"有什么区别

python - 获取 Pandas read_csv() 读入的 dtypes 字典

java - Spring 休息模板 : Parsing using @JsonIgnore causes values to be null

ios - 获取嵌套 JSON 中的每个对象