json - 使用 jq 合并两个文件
问题描述
我有两个文件。
第一的:
[
{ "person1": [] },
{ "person2": [] }
]
第二:
[
{
"person2": { "attribute1": "wer", "attribute2": "sdf" }
},
{
"person2": { "attribute1": "ert", "attribute2": "dfg" }
},
{
"person2": { "attribute1": "rty", "attribute2": "fgh" }
},
{
"person3": { "attribute1": "tyu", "attribute2": "ghj" }
},
{
"person1": { "attribute1": "yui", "attribute2": "hjk" }
}
]
我尝试合并它们,使用jq
. 对于第一个文件中的每个人(在第二个文件中可能有更多人,应该忽略)创建它的属性列表。所以输出应该是这样的:
[
{
"person1":
[
{ "attribute1": "yui", "attribute2": "hjk" }
]
},
{
"person2":
[
{ "attribute1": "wer", "attribute2": "sdf" },
{ "attribute1": "ert", "attribute2": "dfg" },
{ "attribute1": "rty", "attribute2": "fgh" }
]
}
]
我尝试了不同的选项,但我无法达到预期的结果。
解决方案
jq 'reduce (input[]|to_entries[]) as $e (add;
if has($e.key) then .[$e.key] += [$e.value] else . end
) | [keys_unsorted[] as $k|{($k): .[$k]}]' file1 file2
推荐阅读
- javascript - JavaScript 语法条件语法?和
- javascript - 如何重命名 Node Js 中数组内的对象的“键”名称?
- perl - 使用 PostgreSQL 14 运行 Ora2Pg
- javascript - initialFiles 中的状态值 null 反应 dropzone
- npm - npm 是否有类似于“yarn licenses generate-disclaimer”的东西
- reactjs - 在 iframe 中打开 account.google.com 身份验证
- powerbi - 想要使用来自不同表 PowerBI 的列名对视觉对象进行切片
- gdal - GDAL VRT 未在 MapServer (MS4W) 中显示
- firebase - 使用用户名而不是在 firebase 中识别用户
- python - 通过 CMake 查找定制 Python 的解释器和开发组件