简体   繁体   English

jq:来自嵌套 JSON 的 Map

[英]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?

You don't need with_entries .你不需要with_entries

map_values(.value)

Online demo在线演示

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

Your attempt你的尝试

.[] | {value}

just misses the update assignment.只是错过了更新分配。

This will work as expected:这将按预期工作:

.[] |= .value
{
  "A": "value_A",
  "B": "value_B"
}

Demo演示

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。

Check it online .上网查一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM