Pass binary data to Jason.encode/2

Hello,

I need to put binary data (read from a binary file) in a JSON structure, along other metadata.

   Jason.encode(
     %{
          timestamp: Timex.now("Europe/Paris"),
          user: datareq.user,
          seed: File.read!(datafile)
    })

This gives me the error:

 %Jason.EncodeError{message: "invalid byte 0xE7 in <<48, 48, 48, 48, 48, 53, 77, 32, 67, 73, 69, 76, 32, 48, 49, 72, 78, 90, 70, 82, 7, 231, 0, 1, 0, 0, 0, 0, 0, 0, 1, 104, 0, 200, 0, 1, 2, 32, 0, 2, 0, 0, 0, 0, 0, 64, 0, 48, 3, 232, ...>>"}} of type Tuple. This protocol is implemented for the following type(s): Atom, BitString, Date, DateTime, Decimal, Float, Integer, List, NaiveDateTime, Postgrex.Copy, Postgrex.Query, Time, URI, Version, Version.Requirement

What would be the right way to achieve this ?

Thanks,

There is no native encoding for binary data in json. You can e.g. base64 encode it to a string and put that in the json.

1 Like