JSON
import "ghost:json"
import { encode, decode } from "ghost:json"
The json module decodes and encodes JSON.
JSON is a language-independent syntax for serializing maps, lists, numbers, strings, booleans, and null, and a common format for exchanging data between applications.
Methods
encode()
Encodes a value to a JSON string. The value must be a map or a list.
json.encode({ foo: 'bar' })
// '{"foo":"bar"}'
json.encode([1, 2, 3])
// '[1,2,3]'
decode()
Decodes a JSON string to a value. The string must be valid JSON; if it isn't, decoding raises a value error. A valid JSON document whose top level is a bare number, string, boolean, or null is also rejected, with help suggesting you wrap it in [ ].
json.decode('{"foo":"bar"}')
// { foo: 'bar' }
json.decode('[1,2,3]')
// [1, 2, 3]
JSON objects come back as maps and JSON arrays as lists, nested to whatever depth the document has. JSON numbers arrive as Ghost numbers, and because JSON does not distinguish whole numbers from decimals, a value that has no fractional part is decoded as a whole number.
data = json.decode('{"window":{"width":1280},"tags":["a","b"]}')
console.log(data.window.width) // >> 1280
console.log(data.tags[1]) // >> b