[英]Using jq how to add the key to the existing JSON data structure
Hello and thanks in advance,您好,在此先感谢您,
So I have the following JSON:所以我有以下JSON:
{
"key1" : {
"someKey": "someValue"
},
"key2" : {
"someKey": "someValue"
}
}
and the output that I'm looking for is:我正在寻找的 output 是:
[
{
"someKey": "someValue",
"$key" : "key1"
},
{
"someKey": "someValue",
"$key" : "key2"
}
]
So basically I need to append the 'key' to the value as a separate property in the value of that key's object using jq.所以基本上我需要使用 jq 将 append 的“键”作为该键的 object 的值中的一个单独属性。
I already figured out how to convert the values into an array, but I cannot figure out how to add the "$key" to the object.我已经想出了如何将值转换为数组,但我不知道如何将“$key”添加到 object。
Please help.请帮忙。 Thanks.
谢谢。
I found the solution using the following command:我使用以下命令找到了解决方案:
[ to_entries[] | {"$key": .key} * .value ]
How this works?这是如何工作的?
The to_entries[]
outputs to_entries[]
输出
{
"key": "key1",
"value": {
"someKey": "someValue"
}
}
{
"key": "key2",
"value": {
"someKey": "someValue"
}
}
Then it pipes this output using '|', after piping it creates an object然后它使用“|”管道此 output,管道后创建 object
{"$key": .key}
Then, using the *
operator, it merges this new object with the object located at the .value
key from each object from the to_entries[]
output. Then, using the
*
operator, it merges this new object with the object located at the .value
key from each object from the to_entries[]
output.
The outermost wrapping with []
just creates an array from the stream.用
[]
包裹的最外层只是从 stream 创建一个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.