Using Json string in the Http Header

Yes, you may use JSON in HTTP headers, given some limitations.

According to the HTTP spec, your header field-body may only contain visible ASCII characters, tab, and space.

Since many JSON encoders (e.g. json_encode in PHP) will encode invisible or non-ASCII characters (e.g. “é” becomes “\u00e9”), you often don’t need to worry about this.

Check the docs for your particular encoder or test it, though, because JSON strings technically allow most any Unicode character. For example, in JavaScript JSON.stringify() does not escape multibyte Unicode, by default. However, you can easily modify it to do so, e.g.

var charsToEncode = /[\u007f-\uffff]/g;
function http_header_safe_json(v) {
  return JSON.stringify(v).replace(charsToEncode,
    function(c) {
      return '\\u'+('000'+c.charCodeAt(0).toString(16)).slice(-4);
    }
  );
}

Source

Alternatively, you can do as @rocketspacer suggested and base64-encode the JSON before inserting it into the header field (e.g. how JWT does it). This makes the JSON unreadable (by humans) in the header, but ensures that it will conform to the spec.


Worth noting, the original ARPA spec (RFC 822) has a special description of this exact use case, and the spirit of this echoes in later specs such as RFC 7230:

Certain field-bodies of headers may be interpreted according to an
internal syntax that some systems may wish to parse.

Also, RFC 822 and RFC 7230 explicitly give no length constraints:

HTTP does not place a predefined limit on the length of each header field or on the length of the header section as a whole, as described in Section 2.5.

Leave a Comment