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

使用jq处理JSON时出现重复输出,如何解决?

解决jq处理JSON时出现重复记录的问题

原始JSON数据

{"cells": [{"source": ["# Get the files in a directory \n", "ls -l \n"]}, {"source": ["# Get the working directory \n", "pwd \n"]}, {"source": ["# Get the network config \n", "ipconfig \n"]}], "metadata": {"kernelspec": {"display_name": "Bash", "language": "bash", "name": "bash"}}}

期望输出结构

{"source": ["# Get the files in a directory \n", "ls -l \n"], "title": "# Get the files in a directory \n"}
{"source": ["# Get the working directory \n", "pwd \n"], "title": "# Get the working directory \n"}
{"source": ["# Get the network config \n", "ipconfig \n"], "title": "# Get the network config \n"}

问题重现

使用以下命令时出现重复记录:

cat test.json | jq '{source: .cells[].source, title: .cells[].source[0] }'

原因分析

命令里同时使用了两次.cells[]遍历,这会触发笛卡尔积:每个source会和所有title组合生成结果,最终导致重复记录。

解决方法

改为遍历单个cell元素,对每个元素单独提取对应字段:

cat test.json | jq '.cells[] | {source: .source, title: .source[0]}'

说明

.cells[]会逐个遍历数组中的每个cell对象,之后针对当前cell,直接提取它的.source作为source字段,再取.source[0]作为title字段,这样就能得到一对一的正确结果,不会产生重复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:03:24