Working with JSON in Gosu

Gosu provides native support for the JavaScript Object Notation (JSON) data format.

Overview of JSON support

Gosu has native support for JavaScript Object Notation (JSON) data format. JSON is an open-standard format that uses human-readable text to transmit data objects consisting of attribute-value pairs, hierarchical data structures, and arrays. Web sites often send or receive small amounts of JSON data as a lightweight alternative to the XML standard. Creation of JSON data and parsing can be implemented in any language or operating system, but is popular due to efficient web browser client-side parsing of JSON in JavaScript.

The JSON format is a binding of name-value pairs where a value is one of the following:

  • A simple type, like a String or a number
  • An object that contains name/value pairs
  • An array of values

JSON itself has no inherent ability to provide type information other than those previously mentioned built-in types. For example, there is no built-in way to encode a record as a specific complex type that represents a person, a car, or a mailing address. Despite widespread use of JSON in web development, there is no standard schema for JSON. There is no XSD or DTD equivalent for JSON such that the publisher of a format can specify the correct data format to expect or validate against. As a consequence, most development environments do minimal validation and treat JSON code as untyped attribute-value pairs.

The native Gosu features called expando objects and dynamic types support the general metaphor of general purpose attribute-value pairs. You can use those Gosu features to generate JSON-like structures with a natural lightweight syntax:

var person: Dynamic = new() {
  :Name = "Andy Applegate",
  :Age = 39
}

This dynamic access can be used to get and set data in a non-type-safe way with little effort.

However, you may want to generate actual JSON data from this type of structure, or parse complex JSON data into a structure that you can naturally navigate from Gosu. Gosu provides a way of generating a type-safe class called a structural type from JSON data, which can assist type-safe Gosu coding with JSON data.

See also