How do I use a value as a key reference in jq?

筅森魡賤 提交于 2021-01-29 11:44:31

问题


I have two JSON files as follows.

One contains a mapping of project to owners.

owners.json

{
  "Project1": "owner1",
  "Project2": "owner2"
}

The second contains a list of projects with extra information:

projects.json

[
  {
    "name": "Project1",
    "base": "A"
  },
  {
    "name": "Project2",
    "base": "B"
  }
]

I'd like to use JQ to merge the two files to look like the following:

output.json

[
  {
    "name": "Project1",
    "owner": "owner1",
    "base": "A"
  },
  {
    "name": "Project2",
    "owner": "owner2",
    "base": "B"
  }
]

My first thought was to try something like this (assuming projects.json is fed on stdin):

jq --slurpFile owners owners.json '.name as $n | [.[] | {name, base, owner: $owners[0].$n}]'

This gives a syntax error relating to the $n in $owners[0].$n. What's the right way to do this in JQ?

Thanks!


回答1:


You need to wrap variable references in square brackets for indexing objects with them. Even though you corrected that your script wouldn't work as arrays can't be indexed with strings (.name as $n part).

And don't bother with slurpfile, there are simpler ways.

$ jq 'input as $owners | map(.owner = $owners[.name])' projects.json owners.json
[
  {
    "name": "Project1",
    "base": "A",
    "owner": "owner1"
  },
  {
    "name": "Project2",
    "base": "B",
    "owner": "owner2"
  }
]


来源:https://stackoverflow.com/questions/61092531/how-do-i-use-a-value-as-a-key-reference-in-jq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!