Search code examples
jsonjquuid

How to populate value with input


From a composer.lock I am creating json output of some fields, like this:

 <composer.lock jq  '.packages[] | {site: "foo", name: .name, version: .version, type: .type}' | jq -s

It works fine:

  {
    "site": "foo",
    "name": "webmozart/path-util",
    "version": "2.3.0",
    "type": "library"
  },
  {
    "site": "foo",
    "name": "webonyx/graphql-php",
    "version": "v14.9.0",
    "type": "library"
  }

but now I want to add a generated value, using uuidgen, but I can't figure out how to do that.

End result would be something like:

  {
    "site": "foo",
    "name": "webmozart/path-util",
    "version": "2.3.0",
    "type": "library",
    "uuid": "c4e97c3c-147d-4360-a601-6b4f6f5e71bb"
  },
  {
    "site": "foo",
    "name": "webonyx/graphql-php",
    "version": "v14.9.0",
    "type": "library",
    "uuid": "6fbe472b-49fe-4064-93f0-09a18a7e1c24"
  }

I think I should use input, but all I tried so far have failed.


Solution

  • If your shell supports process substitution, you can avoid a two-pass solution as follows:

    jq -nR  --argfile input composer.lock '
      $input 
      | .packages[]  
      | {site: "foo", name: .name, version: .version, type: .type, id: input}
     ' < <(while true; do uuidgen; done)
    

    The point here is that by using process substitution as above, the termination of the "consumer" (jq) will also terminate the "producer" of UUIDs.