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

如何使用jq流式模式为大JSON提取的每条记录添加指定新key?

问题原因

你之前的命令错误核心是:过滤后只保留了data数组对应的流片段,上层的id、tooldatareports等字段已经被截断,自然无法从当前的fromstream结果里读取到这些值。

解决命令

流模式下需要先暂存路径固定的上层字段,再匹配对应toolid和data数组片段拼接,全程不会加载全量JSON到内存,适配大文件场景:

jq -cn --stream '
# 暂存顶层固定字段
first(inputs | select(.[0] == ["id","bioguide"]) | .[1]) as $bioguide
| first(inputs | select(.[0] == ["id","thomas"]) | .[1]) as $thomas
| first(inputs | select(.[0] == ["tooldatareports",0,"name"]) | .[1]) as $report_name
# 遍历流数据组装结果
| reduce inputs as $i (
    {current_toolid: null, results: []};
    if $i[0] | startswith(["tooldatareports",0,"tooldata"]) then
        # 暂存当前toolid
        if $i[0][-2:] == ["toolid","value"] then
            .current_toolid = $i[1]
        # 匹配到data数组结束时,组装完整对象
        elif $i[0] | index("data") == (.[0] | length -1) and $i[1] == null then
            $i[0] | .[0:-1] as $data_path
            | fromstream( inputs | label $out | while(.[0] | startswith($data_path); ., break $out) ) as $data
            | .results += [{$bioguide, $thomas, "name": $report_name, "toolid": .current_toolid, $data}]
        else . end
    else . end
) | .results
' data.json

输出验证

用你提供的示例JSON作为输入,上述命令输出完全匹配你给出的预期结构。

内容的提问来源于stack exchange,提问作者CYC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:18:03