使用Python或jq为ndjson文件的非index行添加外层封装
NDJSON字段封装解决方案
不需要必须使用Python的JSON模块实现该需求,使用jq可以更简便地完成处理,两种可行方案如下:
1. jq实现方案
jq本身原生支持NDJSON格式的逐行处理,仅需一行命令即可得到目标结果:
jq -c 'if has("index") then . else {name: .} end' 你的输入文件.ndjson > 输出文件.ndjson
参数说明:
-c代表输出紧凑格式的JSON,符合NDJSON每行一个独立JSON对象的要求- 逻辑说明:逐行判断当前JSON对象是否包含
index键,包含则直接输出原内容,不包含则将原JSON内容封装为name键的取值
2. Python实现方案
如果不希望额外安装jq工具,也可以用Python实现,推荐使用标准库的json模块处理,避免纯文本拼接容易出现的转义字符、格式错位等问题,实现代码如下:
import json # 替换为你的输入、输出文件路径 input_path = "source.ndjson" output_path = "result.ndjson" with open(input_path, "r", encoding="utf-8") as infile, open(output_path, "w", encoding="utf-8") as outfile: for line in infile: line = line.strip() if not line: # 跳过空行 continue json_obj = json.loads(line) if "index" not in json_obj: json_obj = {"name": json_obj} # 写回结果,ensure_ascii=False兼容非英文字符 outfile.write(json.dumps(json_obj, ensure_ascii=False) + "\n")
内容的提问来源于stack exchange,提问作者Stpete111
相关产品推荐
相关产品推荐

