JSONATA tips: generating random numbers, timestamps and strings

I thought I would share this - just some generation tricks I use.

Hope it helps.

{
    /* BASICS */

    /* random real number between 0 and 1*/
    "random real number": $random(),
    /* unix epoch timestamp */
    "timestamp": $toMillis($now()),
    /* guid generation - this only works in our app because we added an extension to the jsonata engine */
    /* "random guid": $uuid() */

    /* DERIVED */

    /* one per millisecond per day (1000 * 60 * 60 * 60 * 24) */
    "sequential number": $toMillis($now()) % 86400000,
    /* random integer 0 to 9999*/
    "random integer": $floor($random() * 10000),
    /* random token generation - 12 characters long, using alphabet 'abc...89-_' with length 64 */
    "random token": $join([0..12].$substring('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_', $floor($random() * 64),1)),
    /* for fun I implemented this as a random token generator */
    "random dashed hex tokens": $join([3,2,5,2].$join([1..$].$substring('0123456789ABCDEF', $floor($random() * 16), 1), ''), '-')
}

Example Output (should be different each time)

{
  "random real number": 0.8861914851876,
  "timestamp": 1724946494212,
  "sequential number": 56894212,
  "random integer": 3000,
  "random token": "yNt_iLFSL1v3L",
  "random dashed hex tokens": "6AA-F2-51619-22"
}

Link to exerciser

2 Likes