1 JS-Expressions
2 A word about design


by Dave Herman (dherman at ccs dot neu dot edu)

This library provides utilities for marshalling and unmarshalling data in the JSON data exchange format. See the JSON web site and the JSON RFC for more information about JSON.

 (require (planet dherman/json:3:0))

1 JS-Expressions

This library defines a subset of Scheme values that can be represented as JSON strings. A JS-Expression, or jsexpr, is one of:

(jsexpr? x)  boolean?
  x : any
Performs a deep check to determine whether x is a jsexpr.

(read-json [in])  jsexpr?
  in : input-port? = (current-input-port)
Reads an immutable jsexpr from a JSON-encoded input port in.

(write-json x [out])  any
  x : jsexpr?
  out : output-port? = (current-output-port)
Writes the jsexpr x, encoded as JSON, to output port out.

(jsexpr->json x)  string?
  x : jsexpr?
Generates a JSON source string for the jsexpr x.

(json->jsexpr s)  jsexpr?
  s : string?
Parses the JSON string s as an immutable jsexpr.

2 A word about design

Because JSON distinguishes syntactically between null, array literals, and object literals, this library uses non-overlapping datatypes for the three corresponding variants of jsexpr.

Since the Scheme null value '() overlaps with lists, there is no natural choice for the jsexpr represented as null. We prefer #\null as the least objectionable option from Scheme’s host of singleton datatypes (note that the #<void> and #<undefined> constants do not have readable and writeable representations, which makes them less convenient choices).

The JSON RFC only states that object literal expressions "SHOULD" contain unique keys, but does not proscribe them entirely. Looking at existing practice, it appears that popular JSON libraries parse object literals with duplicate keys by simply picking one of the key-value pairs and discarding the others with the same key. This behavior is naturally paralleled by PLT Scheme hash tables, making them a natural analog.

Finally, the JSON RFC is almost completely silent about the order of key-value pairs. While the RFC only specifies the syntax of JSON, which of course always must represent object literals as an ordered collection, the introduction states:

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

In practice, JSON libraries discard the order of object literals in parsed JSON text and make no guarantees about the order of generated object literals. This again makes hash tables a good choice for representing as JSON object literals.