11

I am developing a Rest API, and I am asking myself:

Is it a good Idea to put base64 encoded data in Json, e.g. for file uploads? What if the base64 contains some of {,},: characters and breaks the json content?

If is not a good idea, what alternatives are widely considered to be best practices?

Jasper
  • 119
  • 8
Dimitrios Desyllas
  • 451
  • 2
  • 4
  • 16
  • How do you define "good idea?" The JSON specification allows strings. Base64 is string data; in fact, it's one way to get binary data into a string form so that you can put it into data containers that are text-based... like JSON. Whether that arrangement adequately meets your needs is a different matter. – Robert Harvey Jun 12 '17 at 20:29
  • 2
    Try using a different content type other than json. `application/octet-stream` may be one approach. – Matthew Jun 12 '17 at 20:30
  • 2
    https://en.wikipedia.org/wiki/Base64 – Robert Harvey Jun 12 '17 at 20:34

1 Answers1

10

Base64 is a safe encoding for JSON.

The downside to using Base64 is that it's quite verbose. It can add significant overhead to your file upload which means longer upload and more bandwidth used. If it's possible I suggest using a binary protocol that supports JSON types. CBOR is a popular one that ElasticSearch uses for document uploads. There is also BSON.

Samuel
  • 9,137
  • 1
  • 25
  • 42
  • 3
    Base64 doesn't contain any of the characters the OP cited anyway. – Robert Harvey Jun 12 '17 at 20:34
  • I thought it didn't :) – Samuel Jun 12 '17 at 20:34
  • @Robert Harvey: Well... I remember one can define his own set of characters to be used for encoding in Base64. There may be a popular set that many people use but it is not certain that one Base64 implementation will use the same set as the next. – Martin Maat Jun 17 '17 at 20:57