JSON is a text-based human-readable data format for transferring data between systems. It looks very similar to JavaScript's object literal (see our objects page) but there are some differences, the most obvious one being that property names have to be given in double quotes (see example below).
There is a standard built-in object in JavaScript called JSON
. It just has 2 methods:
JSON.stringify (my_value)
// converts my_value to a JSON Stringvar x = JSON.parse (JSON_string)
// converts JSON to a JavaScript objectThe methods are used exactly as shown: you do not construct a JSON object first.
The following is an example from my program The Forest (at myforest.uk). The program is (among other things) a simulation of the sport of orienteering. The sport involves navigating between control points marked on the ground by red/white flags and on a map (carried by each competitor) by purple circles.
The point is that an orienteering course has a definite structure which can well be described by JSON (and indeed JSON is used in The Forest program). In words the structure is as follows, in which positions are given by (x, y) ground coordinates (like Ordnance Survey grid references).
Course title Start position For each control point marker: Position Id code Description Offset for placing number on map Finish position
So the following is a real example of such a course (as in the map above) encoded as JSON.
{"title":"Easy short, 1.6km","controls":[{"marker":{"x":608,"y":1932,"code":"KI"},"description":"water hole","offset":{"x":20,"y":0}},{"marker":{"x":552,"y":2019,"code":"GR"},"description":"boulder","offset":{"x":20,"y":10}},{"marker":{"x":719,"y":2142,"code":"RK"},"description":"mineshaft","offset":{"x":-5,"y":35}},{"marker":{"x":853,"y":2087,"code":"VH"},"description":"rootstock","offset":{"x":-5,"y":35}},{"marker":{"x":977,"y":2123,"code":"PR"},"description":"boulder","offset":{"x":-5,"y":35}},{"marker":{"x":1129,"y":1990,"code":"LO"},"description":"boulder","offset":{"x":-5,"y":35}},{"marker":{"x":1043,"y":1761,"code":"DT"},"description":"knoll","offset":{"x":20,"y":0}},{"marker":{"x":784,"y":1749,"code":"EH"},"description":"boulder","offset":{"x":-30,"y":15}}],"start":{"x":720,"y":1850},"finish":{"x":640,"y":1840}}
More information about JSON can be found on Wikipedia and on Mozilla's JavaScript reference site.
The main reason for introducing JSON at this point will be seen on the next page.