Search code examples
jsonappendjq

jq - Append element after picking


System Information

jq: 1.7

Pick

  • Following command works correctly as expected:
jq 'pick(.id,.title,.webpage_url,.channel,.duration_string,.upload_date)' *.info.json
{
  "id": "uO8Sn0Xch1s",
  "title": "A transformative new way of classifying foods 🍔🍕🍟 BBC",
  "webpage_url": "https://www.youtube.com/watch?v=uO8Sn0Xch1s",
  "channel": "BBC",
  "duration_string": "4:19",
  "upload_date": "20210701"
}

Pick and Append

$ Date=$(date +%Y-%m-%d)
$ jq 'pick(.id,.title,.webpage_url,.channel,.duration_string,.upload_date)' *.info.json \
  | jq --arg Date="$Date" '. += {"date": $Date}'
{
  "id": "uO8Sn0Xch1s",
  "title": "A transformative new way of classifying foods 🍔🍕🍟 BBC",
  "webpage_url": "https://www.youtube.com/watch?v=uO8Sn0Xch1s",
  "channel": "BBC",
  "duration_string": "4:19",
  "upload_date": "20210701"
}

Issue

  1. Pick and Append produces same output as Pick and is not appending date. Why and how can I correct this?
  2. also tried + instead of +=, both didn't work (but should work as per Reference 2)

Expected Output

{
  "id": "uO8Sn0Xch1s",
  "title": "A transformative new way of classifying foods 🍔🍕🍟 BBC",
  "webpage_url": "https://www.youtube.com/watch?v=uO8Sn0Xch1s",
  "channel": "BBC",
  "duration_string": "4:19",
  "upload_date": "20210701",
  "date": "2024-05-10"
}

Reference


Solution

  • As suggested by @pmf in the comments

    $ Date=$(date +%Y-%m-%d)
    $ jq 'pick(.id,.title,.webpage_url,.channel,.duration_string,.upload_date)' *.info.json \
      | jq --arg Date="$Date" '. += {"date": $Date}'
    
    • Building upon above suggestion, following is more concise
    jq --arg Date "$Date" 'pick(.id,.title,.webpage_url,.channel,.duration_string,.upload_date) + {"date": $Date}' *.info.json