You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 05:36:07