CouchDB uses JavaScript Object Notation (JSON) for data storage, a lightweight format based on a subset of JavaScipt syntax. One of the best bits about JSON is that it’s easy to read and write by hand, much more so than something like XML. We can parse it naturally with JavaScript, because it shares part of the same syntax. This comes in really handy when we’re building dynamic Web applications and we want to fetch some data from the server.
Here’s a sample JSON document:
{
"Subject": "I like Plankton",
"Author": "Rusty",
"PostedDate": "2006-08-15T17:30:12-04:00",
"Tags": [
"plankton",
"baseball",
"decisions"
],
"Body": "I decided today that I don't like baseball. I like plankton."
}
You can see that the general structure is based around key/value pairs, and lists of things. There’s a few extra things we need to know though, before we can call ourselves JSON masters. JSON has a number of basic data types that you can use. We’ll cover them all in this appendix.
Numbers
You can have positive integers:
Or negative integers:
Or floating point numbers:
Or scientific notation:
|
There is a subtle, but important, difference between floating point numbers and decimals. When you use a number like 15.7, this will be interpreted as 15.699999999999999 by most clients, which may be problematic for your application. For this reason, currency values are usually better represented as strings in JSON. A string like "15.7" will be interpreted as "15.7" by every JSON client.
|
Strings
You can use strings for values:
You have to escape some special characters, like forward slashes:
"Address": "http:\/\/example.org\/rusty"
The JSON site at http://www.json.org/ has details on what needs to be escaped.
Booleans
You can have boolean true values:
Of boolean false values:
Arrays
An array is a list of values:
"Tags": ["plankton", "baseball", "decisions"]
An array can contain any other data type, including arrays:
"Context": ["dog", [1, true], {"Location": "puddle"}]
Objects
An object is a list of key/value pairs:
{"Subject": "I like Plankton", "Author": "Rusty"}
Nulls
You can have null values: