gpt4 book ai didi

json - 使用jq将多个JSON的一个属性连接到一个文件中

转载 作者:行者123 更新时间:2023-12-05 00:46:55 26 4
gpt4 key购买 nike

我有多个格式相似的 JSON 文件,这里有两个例子:

message_1.json

{
"participants": [
{
"name": "Person One"
},
{
"name": "Person Two"
}
],

"messages": [
{
"sender_name": "Person One",
"timestamp_ms": 0002,
"content": "Text2.",
"type": "Generic"
},
{
"sender_name": "Person Two",
"timestamp_ms": 0001,
"content": "Text1.",
"type": "Generic"
}
],
"title": "Person One",
"is_still_participant": true,
"thread_type": "Regular",
"thread_path": "inbox/SomeString"
}

message_2.json

{
"participants": [
{
"name": "Person One"
},
{
"name": "Person Two"
}
],

"messages": [
{
"sender_name": "Person Two",
"timestamp_ms": 0004,
"content": "Text4.",
"type": "Generic"
},
{
"sender_name": "Person One",
"timestamp_ms": 0003,
"content": "Text3.",
"type": "Generic"
}
],
"title": "Person One",
"is_still_participant": true,
"thread_type": "Regular",
"thread_path": "inbox/SomeString"
}

有没有一种方法可以使用 jq 来合并 JSON 文件,以便连接 messages 属性(顺序无关紧要)而其他的则单独保留?

合并 message_1.json 和 message_2.json 的结果如下所示:

消息.json

{
"participants": [
{
"name": "Person One"
},
{
"name": "Person Two"
}
],

"messages": [
{
"sender_name": "Person One",
"timestamp_ms": 0002,
"content": "Text2.",
"type": "Generic"
},
{
"sender_name": "Person Two",
"timestamp_ms": 0001,
"content": "Text1.",
"type": "Generic"
},
{
"sender_name": "Person Two",
"timestamp_ms": 0004,
"content": "Text4.",
"type": "Generic"
},
{
"sender_name": "Person One",
"timestamp_ms": 0003,
"content": "Text3.",
"type": "Generic"
}
],
"title": "Person One",
"is_still_participant": true,
"thread_type": "Regular",
"thread_path": "inbox/SomeString"
}

我有 11 个 JSON 文件,message_1.json,...,message_11.json。我想将它们全部合并到一个 messages.json 文件中,该文件包含 JSON 文件中的所有消息。我如何通过 bash 使用 jq 来做到这一点?

最佳答案

这是一种方法,它的优点是不需要 -s 选项,这会消耗比必要更多的内存:

jq 'reduce inputs as $in (.;
.messages += $in.messages)
' $(for i in $(seq 1 11); do echo message_$i.json ; done)

请注意,在这种情况下,调用 jq 时应不带 -n 选项。

关于json - 使用jq将多个JSON的一个属性连接到一个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59975714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com