A set of useful APIs for dealing with JSON documents from Golo.
The implementation is backed by json-simple. While
json-simple
only supports encoding from lists and maps, this API brings support for sets, arrays,
Golo tuples, dynamic objects and structs.
JSON augmentations for structs.
Conveniently adds a toJSON()
method, which is equivalent to calling JSON.stringify()
:
struct Person = { name, age, email }
# (...)
Person("Mr Bean", "mrbean@outlook.com", 64): toJSON()
Populates the elements of a struct based on the values found in a JSON string.
let str = JSON.stringify(map[
["name", "Foo"],
["email", "foo@gmail.com"],
["age", 99],
["gender", "N/A"]
])
let foo = Person(): updateFromJSON(str)
Note that missing entries from the JSON data yield null
values in the struct.
Provides a mixin for dynamic objects that includes a toJSON()
method:
object: mixin(JSON.dynamicObjectMixin()): toJSON()
which is equivalent to:
JSON.stringify(object)
Parses a JSON string and gives an object representation as a list or map collection:
let data = JSON.parse(text)
println(data: get("name"))
Takes any know object, and gives a JSON string representation:
let data = map[
["name", "Somebody"],
["age", 69],
["friends", list[
"Mr Bean", "John B", "Larry"
]]
]
let asText = JSON.stringify(data)
obj
may be a list, an array, a set, a map, a tuple, a dynamic object or a struct. If obj
is from
another type then its string representation is given according to obj: toString()
or "null"
if
obj
is null
.
Returns a new dynamic object from a JSON string where each first-level entry is mapped into the dynamic object:
let obj = JSON.toDynamicObject(JSON.stringify(map[
["a", "1"], ["b", "2"]
]))
println(obj: a())
println(obj: b())