MongooseWhere programmers kick back and build silly things together.

All help topics · Link to this topic

Showing help on 'generate_json()'

Syntax: generate_json (ANY value [, STR mode [, ANY disable_binary_escapes]])

Returns the JSON representation of the MOO value.

MOO supports a richer set of values than JSON allows. The optional mode specifies how this function handles the conversion of MOO values into their JSON representation.

The common subset mode, specified by the literal mode string "common-subset", is the default conversion mode. In this mode, strings, numbers, and booleans are translated with fidelity between MOO types and JSON types. All other types are treated as alternative representations of the string type. This mode is useful for integration with non-MOO applications.

The embedded types mode, specified by the literal mode string "embedded-types", adds type information. Specifically, values other than strings, numbers, and booleans, which carry implicit type information, are converted into strings with type information appended. The converted string consists of the string representation of the value (as if tostr() were applied) followed by the pipe (|) character and the type. This mode is useful for serializing/deserializing objects and collections of MOO values.

The optional disable_binary_escapes argument controls whether MOO binary string sequences (like ~08 or ~1F) are converted to JSON escape sequences. By default, these sequences are converted (e.g., ~08 becomes \b). If disable_binary_escapes is true, these sequences pass through unchanged.

generate_json([]) => "{}"
generate_json(["foo" -> "bar"]) => "{\"foo\":\"bar\"}"
generate_json(["foo" -> "bar"], "common-subset") => "{\"foo\":\"bar\"}"
generate_json(["foo" -> "bar"], "embedded-types") => "{\"foo\":\"bar\"}"
generate_json(["foo" -> 1.1]) => "{\"foo\":1.1}"
generate_json(["foo" -> 1.1], "common-subset") => "{\"foo\":1.1}"
generate_json(["foo" -> 1.1], "embedded-types") => "{\"foo\":1.1}"
generate_json(["foo" -> true, "bar" -> false]) => "{\"bar\":false,\"foo\":true}"
generate_json(["foo" -> #1]) => "{\"foo\":\"#1\"}"
generate_json(["foo" -> #1], "common-subset") => "{\"foo\":\"#1\"}"
generate_json(["foo" -> #1], "embedded-types") => "{\"foo\":\"#1|obj\"}"
generate_json(["foo" -> E_PERM]) => "{\"foo\":\"E_PERM\"}"
generate_json(["foo" -> E_PERM], "common-subset") => "{\"foo\":\"E_PERM\"}"
generate_json(["foo" -> E_PERM], "embedded-types") => "{\"foo\":\"E_PERM|err\"}"

JSON keys must be strings, so regardless of the mode, the key will be converted to a string value.

generate_json([1 -> 2]) => "{\"1\":2}"
generate_json([1 -> 2], "common-subset") => "{\"1\":2}"
generate_json([1 -> 2], "embedded-types") => "{\"1|int\":2}"
generate_json([#1 -> 2], "embedded-types") => "{\"#1|obj\":2}"