[英]jq: Map from nested JSON
I have the following JSON:我有以下 JSON:
{
"A": {
"type": "string",
"value": "value_A"
},
"B": {
"type": "string",
"value": "value_B"
}
}
...and am trying to use JQ to result in the following: ...并尝试使用 JQ 来产生以下结果:
Desired Output所需 Output
{
"A": "value_A",
"B": "value_B"
}
...where the key takes the direct value of node.value
. ...其中键采用
node.value
的直接值。
My current attempt:我目前的尝试:
.[] | {value}
...returns the following: ...返回以下内容:
{
"value": "value_A"
}
{
"value": "value_B"
}
How can I use JQ to produce the desired JSON?如何使用 JQ 生产所需的 JSON?
with_entries
helps: with_entries
帮助:
with_entries(.value |= .value)
which is short for to_entries | map(.value |=.value) | from_entries
to_entries | map(.value |=.value) | from_entries
to_entries | map(.value |=.value) | from_entries
to_entries
transforms an object of form {a:b}
into an array in the form [{key:a, value:b}]
, so in your example: to_entries
将形式为{a:b}
的 object 转换为形式为[{key:a, value:b}]
的数组,因此在您的示例中:
{
"key": "A",
"value": {
"type": "string",
"value": "value_A"
}
}
.value |=.value
then assigns the content of .value.value
to .value
, leaving you with: .value |=.value
然后将.value.value
的内容分配给.value
,留下:
{
"key": "A",
"value": "value_A"
}
which is then converted to an object again by from_entries
(repeated from above: with_entries(f)
is equivalent to from_entries|map(f)|from_entries
)然后由 from_entries 再次转换为
from_entries
(从上面重复: with_entries(f)
等效于from_entries|map(f)|from_entries
)
Use the function map_values()
:使用 function
map_values()
:
map_values(.value)
It runs the filter passed as argument to each value of the input object, collects the results and associates them with the keys of the input object and returns an object.它运行作为参数传递给输入 object 的每个值的过滤器,收集结果并将它们与输入 object 的键相关联,并返回 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.