Dump binary file contents in a JSON array

I have a binary file that I would like to pack as a JSON array like so:

  "content": [0, 23, 45,...]

Right now I dump the file using hexdump into a separate file (to print as unsigned u8’s with commas)and manually paste those contents in the array:

hexdump -ve '1/1 "%u," foo.bin > foo_arr

Looking for a better way to achieve this preferably over the command line (jq, standard *nix tools), JavaScript could work as well but I’d rather avoid it.


Here’s one option:

hexdump -ve '1/1 "%un"' foo.bin | jq -s '{content: .}'

Here, I use jq‘s -s flag (“slurp”) to read in all the lines of stdin as a single array, then simply use that array as the value of content.

For example:

$ python -c 'open("foo.bin", "wb").write(b"abc")'
$ hexdump -ve '1/1 "%un"' foo.bin | jq -s '{content: .}'
  "content": [