티스토리 수익 글 보기

티스토리 수익 글 보기

Note:“> ]> A JSON Encoding for HTTP Field Values greenbytes GmbH
Hafenweg 16 Münster48155 Germany julian.reschke@greenbytes.de http://greenbytes.de/tech/webdav/
Applications and Real-Time HTTP JSON Field Value This document establishes a convention for use of JSON-encoded field values in new HTTP fields. Distribution of this document is unlimited. Although this is not a work item of the HTTPbis Working Group, comments should be sent to the Hypertext Transfer Protocol (HTTP) mailing list at ietf-http-wg@w3.org, which may be joined by sending a message with subject “subscribe” to ietf-http-wg-request@w3.org. Discussions of the HTTPbis Working Group are archived at . XML versions and latest edits for this document are available from . The changes in this draft are summarized in .
Defining syntax for new HTTP fields () is non-trivial. Among the commonly encountered problems are:
  • There is no common syntax for complex field values. Several well-known fields do use a similarly looking syntax, but it is hard to write generic parsing code that will both correctly handle valid field values but also reject invalid ones.
  • The HTTP message format allows field lines to repeat, so field syntax needs to be designed in a way that these cases are either meaningful, or can be unambiguously detected and rejected.
  • HTTP does not define a character encoding scheme (), so fields are either stuck with US-ASCII (), or need out-of-band information to decide what encoding scheme is used. Furthermore, APIs usually assume a default encoding scheme in order to map from octet sequences to strings (for instance, uses the IDL type “ByteString”, effectively resulting in the ISO-8859-1 character encoding scheme being used).
(See for a summary of considerations for new fields.) This specification addresses the issues listed above by defining both a generic JSON-based () data model and a concrete wire format that can be used in definitions of new fields, where the goals were:
  • to be compatible with field recombination when field lines occur multiple times in a single message (), and
  • not to use any problematic characters in the field value (non-ASCII characters and certain whitespace characters).
Relation to “Structured Field Values for HTTP” () “Structured Field Values for HTTP”, an IETF RFC on the Standards Track, is a different approach to this set of problems. It uses a more compact notation, similar to what is used in existing header fields, and avoids several potential interoperability problems inherent to the use of JSON. In general, that format is preferred for newly defined fields. The JSON-based format defined by this document might however be useful in case the data that needs to be transferred is already in JSON format, or features not covered by “Structured Field Values” are needed. See for more details.
In HTTP, field lines with the same field name can occur multiple times within a single message (). When this happens, recipients are allowed to combine the field line values using commas as delimiter, forming a combined “field value”. This rule matches nicely JSON’s array format (). Thus, the basic data model used here is the JSON array. Field definitions that need only a single value can restrict themselves to arrays of length 1, and are encouraged to define error handling in case more values are received (such as “first wins”, “last wins”, or “abort with fatal error message”). JSON arrays are mapped to field values by creating a sequence of serialized member elements, separated by commas and optionally whitespace. This is equivalent to using the full JSON array format, while leaving out the “begin-array” (‘[‘) and “end-array” (‘]’) delimiters. The ABNF character names and classes below are used (copied from ): CR = %x0D ; carriage return HTAB = %x09 ; horizontal tab LF = %x0A ; line feed SP = %x20 ; space VCHAR = %x21-7E ; visible (printing) characters Characters in JSON strings that are not allowed or discouraged in HTTP field values — that is, not in the “VCHAR” definition — need to be represented using JSON’s “backslash” escaping mechanism (). The control characters CR, LF, and HTAB do not appear inside JSON strings, but can be used outside (line breaks, indentation etc.). These characters need to be either stripped or replaced by space characters (ABNF “SP”). Formally, using the HTTP specification’s ABNF extensions defined in : json-field-value = #json-field-item json-field-item = JSON-Text ; see , ; post-processed so that only VCHAR characters ; are used
To map a JSON array to an HTTP field value, process each array element separately by:
  1. generating the JSON representation,
  2. stripping all JSON control characters (CR, HTAB, LF), or replacing them by space (“SP”) characters,
  3. replacing all remaining non-VSPACE characters by the equivalent backslash-escape sequence ().
The resulting list of strings is transformed into an HTTP field value by combining them using comma (%x2C) plus optional SP as delimiter, and encoding the resulting string into an octet sequence using the US-ASCII character encoding scheme ().
With the JSON data below, containing the non-ASCII characters ü and : [ { “destination”: “Münster”, “price”: 123, “currency”: “€” } ] The generated field value would be: { “destination”: “M\u00FCnster”, “price”: 123, “currency”: “\u20AC” }
To map a set of HTTP field line values to a JSON array:
  1. combine all field line values into a single field value as per ,
  2. add a leading begin-array (“[“) octet and a trailing end-array (“]”) octet, then
  3. run the resulting octet sequence through a JSON parser.
The result of the parsing operation is either an error (in which case the field values needs to be considered invalid), or a JSON array.
An HTTP message containing the field lines: Example: “\u221E” Example: {“date”:”2012-08-25″} Example: [17,42] would be parsed into the JSON array below: [ “∞”, { “date”: “2012-08-25” }, [ 17, 42 ] ]
Specifications defining new HTTP fields need to take the considerations listed in into account. Many of these will already be accounted for by using the format defined in this specification. Readers of HTTP-related specifications frequently expect an ABNF definition of the field value syntax. This is not really needed here, as the actual syntax is JSON text, as defined in . A very simple way to use this JSON encoding thus is just to cite this specification — specifically the “json-field-value” ABNF production defined in — and otherwise not to talk about the details of the field syntax at all. An alternative approach is just to repeat the ABNF-related parts from . This frees the specification from defining the concrete on-the-wire syntax. What’s left is defining the field value in terms of a JSON array. An important aspect is the question of extensibility, e.g. how recipients ought to treat unknown field names. In general, a “must ignore” approach will allow protocols to evolve without versioning or even using entire new field names.
This JSON-based syntax will only apply to newly introduced fields, thus backwards compatibility is not a problem. That being said, it is conceivable that there is existing code that might trip over double quotes not being used for HTTP’s quoted-string syntax ().
The “I-JSON Message Format” specification () addresses known JSON interoperability pain points. This specification borrows from the requirements made over there:
This specification requires that field values use only US-ASCII characters, and thus by definition uses a subset of UTF-8 (). Furthermore, escape sequences in JSON strings () — both in object member names and string values — are not allowed to represent non-Unicode code points such as unpaired surrogates or Noncharacters (see “General Structure” in ).
Be aware of the issues around number precision, as discussed in .
As described in , JSON parser implementations differ in the handling of duplicate object names. Therefore, senders are not allowed to use duplicate object names, and recipients are advised to either treat field values with duplicate names as invalid (consistent with ) or use the lexically last value (consistent with ). Furthermore, ordering of object members is not significant and can not be relied upon.
In current versions of HTTP, field values are represented by octet sequences, usually used to transmit ASCII characters, with restrictions on the use of certain control characters, and no associated default character encoding, nor a way to describe it (). This specification maps all characters which can cause problems to JSON escape sequences, thereby solving the HTTP field internationalization problem. Future specifications of HTTP might change to allow non-ASCII characters natively. In that case, fields using the syntax defined by this specification would have a simple migration path (by just stopping to require escaping of non-ASCII characters).
Using JSON-shaped field values is believed to not introduce any new threads beyond those described in , namely the risk of recipients using the wrong tools to parse them. Other than that, any syntax that makes extensions easy can be used to smuggle information through field values; however, this concern is shared with other widely used formats, such as those using parameters in the form of name/value pairs.
The Unicode Standard The Unicode Consortium Information technology — 8-bit single-byte coded graphic character sets — Part 1: Latin alphabet No. 1 International Organization for Standardization ECMA-262 6th Edition, The ECMAScript 2015 Language Specification Ecma International Unicode Character Repertoire Subsets UTF-8, a transformation format of ISO 10646 XMLHttpRequest WhatWG
Type in Structured Fields in JSON-based Fields
Integer
(restricted to 15 digits)
Decimal
(a fixed point decimal restricted to 12 + 3 digits)
String and
Strings only support ASCII (), but “Display Strings” cover anything encodable as (that excludes surrogates ()). JSON strings can transport any Unicode code point, due to the “\uxxxx” escape notation.
Token not available, but can be mapped to strings
Byte Sequence not available, usually mapped to strings using base64 encoding
Boolean
Date not available, usually mapped to Strings or Numbers
Structured Fields provide more data types (such as “token” or “byte sequence”). Numbers are restricted, avoiding the JSON interop problems described in .
Structured Fields define Lists (), similar to JSON arrays (), and Dictionaries (), similar to JSON objects (). In addition, most items in Structured Fields can be parametrized (), attaching a dictionary-like structure to the value. To emulate this in JSON based field, an additional nesting of objects would be needed. Finally, nesting of data structures is intentionally limited to two levels (see for the motivation).
See for a proof-of-concept (in development).
Editorial fixes + working on the TODOs.
Mention slightly increased risk of smuggling information in header field values.
Mention Kazuho Oku’s proposal for abbreviated forms. Added a bit of text about the motivation for a concrete JSON subset (ack Cory Benfield). Expand I18N section.
Mention relation to KEY header field.
Between June and December 2016, this was a work item of the HTTP working group (see ). Work (if any) continues now on . Changes made while this was a work item of the HTTP Working Group:
Added example for “Accept-Encoding” (inspired by Kazuho’s feedback), showing a potential way to optimize the format when default values apply.
Add interop discussion, building on I-JSON and ECMA-262 (see ).
Move non-essential parts into appendix. Updated XHR reference.
Add meat to “Using this Format in Header Field Definitions”. Add a few lines on the relation to “Key”. Summarize current use of the format.
RFC 5987 is obsoleted by RFC 8187. Update CLEARSITE comment.
Update JSON and HSTRUCT references. FEATUREPOL doesn’t use JSON syntax anymore.
Update HSTRUCT reference. Update notes about CLEARSITE and FEATUREPOL.
Update HSTRUCT and FEATUREPOL references. Update note about REPORTING. Changed category to “informational”.
Update HSTRUCT reference.
Update HSTRUCT reference. Update note about FEATUREPOL (now using Structured Fields). Reference instead if RFC723* and adjust (header) field terminology accordingly. Remove discussion about the relation to KEY (as that spec is dormant: ). Remove appendices “Examples” and “Discussion”. Mark “Use of JSON Field Value Encoding in the Wild” for removal in RFC.
Update HTTP reference and update terminology some more. Update HSTRUCT reference (now RFC 8941).
Update HTTP reference. Mention test implementation. Clarify that Unicode unpaired surrogates or Noncharacters must not be sent. Rewrite text about , add appendix comparing both formats. And send/receive examples.
Update HTTP reference. Mention .
Cite instead RFC 8941. Cite and , and rework comparison chart for strings. Removed appendix about use of this format in W3C specifications; they all have moved over to Structured Fields.
Thanks go to the Hypertext Transfer Protocol Working Group participants.