[Haskell-cafe] Ordered JSON objects?

Tobias Dammers tdammers at gmail.com
Wed Dec 17 09:01:40 UTC 2014


On Wed, Dec 17, 2014 at 12:12:00PM +1300, Richard A. O'Keefe wrote:
> 
> On 16/12/2014, at 9:39 pm, Tobias Dammers <tdammers at gmail.com> wrote:
> > No, that's not what I meant. By "ordered", I meant that the in-memory
> > representation of the document should maintain file order.
> 
> You did consult RFC 4627, right?
> 
> So if you depend on the order of the name/value pairs in
> a JSON object, you doing something surpassing strange and
> risky.

No need to go all RTFM on me; "JSON objects are unordered" is exactly
what I was basing my reasoning on. I am not planning on depending on the
order of something that is unordered by definition.

However, my requirements are:

1. File format must be valid JSON (or occasionally YAML, or at least the
   JSON-isomorphic subset)
2. I need to represent ordered key/value collections
3. Conversion from JSON to the internal data type must be total (i.e.,
   any valid JSON document must be accepted and converted to the most
   reasonable internal representation).

Since JSON objects are (semantically) unordered, and the only way to get
an ordered collection in JSON is through an array, my choices are:

a) Use something that looks like JSON but defines objects as ordered
key/value collections; this is something I *really* don't want, because
it can break so many assumptions, and I would have to write my own JSON
(and YAML) parsers for no good reason.
b) Use an array of one-element objects.
c) Use an array of keys and a key/value object side-by side.
d) Use an array of objects, with a 'magic' property providing a tag
name, and another magic property providing the payload value.
e) Exactly like d), but gracefully accept other array elements, treating
them as unnamed values.

What I have implemented now is option e), with "_name" and "_value" for
the magic properties; if neither is given, the element itself becomes an
unnamed value, and can only be looked up by position; if a name is given
but no value, it becomes a named null entry; if both are given, a proper
name/value pair is generated.

I'm still working out the details of if and what to throw away when an
entry has both a "_value" and other properties, but other than that, I
think this is as good as it gets.

-- 
Tobias Dammers - tobias at twokings.nl - 070-3457628 - www.twokings.nl
Maandag t/m donderdag van 9.00 tot 17.30
Voor dringende vragen, mail naar support at twokings.nl


More information about the Haskell-Cafe mailing list