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

使用jq将成对JSON对象合并为结构化JSON数组

jq 实现成对JSON对象合并方案

需求说明

现有如下JSON对象序列(每行一个独立JSON对象):

{"field": "@timestamp","value": "2024-08-20 23:00:13.426"}
{"field": "@message","value": "Started-1"}
{"field": "@timestamp","value": "2024-08-20 23:00:13.427"}
{"field": "@message","value": "Started-2"}

需要将每一对@timestamp与@message对象合并为包含对应属性的单个对象,最终生成如下JSON数组:

[
  {"@timestamp": "2024-08-20 23:00:13.426","@message": "Started-1"},
  {"@timestamp": "2024-08-20 23:00:13.427","@message": "Started-2"}
]

jq 实现命令

文件输入方式

jq -n '[inputs | {( .field ): .value}] | _nwise(2) | add' input.json

管道输入方式

如果通过管道传递输入内容,可使用:

cat input.json | jq -n '[inputs | {( .field ): .value}] | _nwise(2) | add'

命令解析

  • -n:启用空输入模式,便于手动构建输出结构,避免输入流开头的干扰
  • inputs:读取所有输入的独立JSON对象
  • {( .field ): .value}:将每个输入对象转换为以field值为键、value值为对应内容的单键对象
  • _nwise(2):将转换后的对象按每2个为一组拆分,确保每组包含一个@timestamp和一个@message对象
  • add:将每组内的两个单键对象合并为一个完整对象
  • 外层[]:将所有合并后的对象包裹为JSON数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:41:01