0

I have a problem with passing variables into jq. Here is example file:

[
  {
    "version": 24,
    "file": "branding/24"
  }
]

and here is my script:

jq --arg value "25" '. += [{"version": $value|tonumber, "file": "branding/$value|tonumber"}]' versions.json >tmp.json && mv tmp.json versions.json

The result is:

[
  {
    "version": 24,
    "file": "branding/24"
  },
  {
    "version": 25,
    "file": "branding/$value|tonumber"
  }
]

Expected result:

[
  {
    "version": 24,
    "file": "branding/24"
  },
  {
    "version": 25,
    "file": "branding/25"
  }
]
peak
  • 105,803
  • 17
  • 152
  • 177
mpiatek
  • 13
  • 4
  • @charlesduffy - This is really about string interpolation, whereas I believe your hyperlinkee was about passing in a value. – peak Feb 23 '21 at 15:26
  • @peak, you're right. I'll try to find a better one, and will reopen if that fails. – Charles Duffy Feb 23 '21 at 15:27
  • @peak, how about [concat 2 fields in json using jq?](https://stackoverflow.com/questions/37710718/concat-2-fields-in-json-using-jq) – Charles Duffy Feb 23 '21 at 15:29

1 Answers1

3

You need to use interpolation to have the filter evaluated.

{"version": $value|tonumber, "file": "branding/\($value|tonumber)"}
chepner
  • 497,756
  • 71
  • 530
  • 681
  • And now I have another question in my example - it is possible to check if json element exists by **version** field by jq-filter and if not then append? – mpiatek Feb 23 '21 at 14:31
  • 2
    @mpiatek, ...yes, it's possible, but it should be a separate question (raised only after a check for other asked/answered instances). On which point, you might find https://stackoverflow.com/a/54109775/14122 to be useful inspiration. – Charles Duffy Feb 23 '21 at 15:13
  • @charlesduffy - Seems SO has granted me some magical powers. In the interests of discoverability, I think this should only be closed if we can find a well-answered question with both elements, as I’m sure there is..... – peak Feb 23 '21 at 15:35
  • @peak, one of the powers that comes with your gold-badge dupehammer (congrats on that, it's well-earned) is the ability to edit the list of duplicates assigned to a question -- and it's a _list_, so a question with two distinct elements can have two duplicates simultaneously attached. The max is something like 5, and that point close-as-too-broad is generally appropriate. – Charles Duffy Feb 23 '21 at 16:07