Andrea
Andrea

Reputation: 20493

Strange JSON in CouchDB

I am learning CouchDB I and like its functionality very much. One things bugs me, though, and it is the claim that CouchDB communicates through JSON.

Actually, JSON requires that the keys for objects are strings, while it is possible, and even advised by Damien Katz himself to have views which return objects whose keys are other objects, or arrays.

This is confusing, since I did not find written anywhere that CouchDB uses a variant of JSON. Moreover, it does not make much sense, for at least two reasons:

  1. when are two keys considered equal? For instance, I assume that if CouchDB allows keys which are not strings, numbers would be allowed. But then the keys 5 and '5' will be different, which is weird since in Javascript they are considered the same.

  2. More importantly, parsing the output of CouchDB will be more difficult, since one cannot use the standard JSON parsers which are available for every language.

Am I just confused in interpreting the above links, or does actually CouchDB return a non-standard JSON output? And if so, how do one works with it?

Upvotes: 3

Views: 1771

Answers (3)

Anand Chitipothu
Anand Chitipothu

Reputation: 4377

Don't get confused between keys of an object and keys of a couchdb view.

Each row in the CouchDB view result contains id, key and value. id is a string and key and value can be any object. It is very common to have non-string values as keys.

Here is a sample view result with non-string keys.

$ curl http://127.0.0.1:5984/blog/_design/posts/_view/by_date
{"total_rows":3,"offset":0,"rows":[
{"id":"88e325c07e897f52766340dc17003322","key":[2010,10,13],"value":null},
{"id":"88e325c07e897f52766340dc17002641","key":[2011,4,5],"value":null},
{"id":"88e325c07e897f52766340dc1700233e","key":[2011,4,23],"value":null}
]}

Upvotes: 4

JasonSmith
JasonSmith

Reputation: 73752

Document IDs (the _id) field must be a string. View keys (the first parameter to emit()) may be any JSON value. You are right, it is a bit confusing.

Two keys are considered equal according to the CouchDB collation specification. Basically, values compare like you would expect:

  • Numbers sort by value
  • Strings sort according to the libicu rules.
  • Arrays sort by comparing first value, second value, etc.

Of course, with document IDs, the only thing that matters is how strings sort since document ids are always strings.

Finally, CouchDB always outputs standard JSON. If you encounter nonstandard JSON from CouchDB that is a bug and the community would want to hear about it.

Upvotes: 5

Dennis Kreminsky
Dennis Kreminsky

Reputation: 2089

I guess this explains it.

enter image description here

On the second thought, keys are parts of map/reduce operations, so I'll have to dig into that.

Upvotes: 1

Related Questions