Search code examples
randomjquuid

jq : Generate UUID in field


I have a requirement to tag records uniquely with UUIDs (for a correlation id). I cant see a direct way to do this via the options, is such a thing possible? If not, is there some kind of workaround that might be able to do this?

Is it even possible to generate a random number or string in jq?


Solution

  • jq currently has no support for UUID generation, so your best bet would be to feed UUIDs in to jq, e.g. along these lines:

    ruby -e 'require "securerandom"; p SecureRandom.uuid' | jq '{uuid: .}'
    {
      "uuid": "5657dd65-a495-4487-9887-c7f0e01645c9"
    }
    

    The PRNG contributions for jq have unfortunately not yet made their way into an official release. For examples of PRNG generators written in jq, see e.g. rosettacode:

    https://rosettacode.org/wiki/Linear_congruential_generator#jq

    Reading from an unbounded stream of UUIDs

    Assuming the availability of a uuid generator such as uuidgen, you could use input or inputs along the following lines:

    jq -nR '[range(0;10) | input]' < <(while true; do uuidgen ; done)
    

    (Notice that an OS pipe has been avoided here.)