JSON
mash.json · Data
mash.json turns JSON text into data a script can use, and data back into JSON text. Web services, webhooks and many exports speak JSON.
How it works
Section titled “How it works”decode gives dictionaries and lists. The default is dictionaries, so data["order"]["ref"] works. Pass false as the second argument and you get objects instead, read with a dot (data.order.ref).
Bad JSON is an error, not null. decode records json decode - check your input and the line gives you nothing. Put an error block after it if the text comes from outside. A web response behaves differently: its json property quietly gives null when the body isn’t valid JSON.
encode writes compact JSON. Dictionaries become objects, lists become arrays. It raises a clear error for a value it can’t write, such as text with broken UTF-8.
Common tasks
Section titled “Common tasks”Read a nested value:
set data to mash.json.decode('{"order": {"ref": "SO-1", "lines": [{"sku": "A", "qty": 2}]}}')printline data["order"]["ref"]printline data["order"]["lines"][0]["sku"]SO-1AWrite JSON for a web service:
printline mash.json.encode({ref: "SO-2", paid: true, lines: [1, 2]}){"ref":"SO-2","paid":true,"lines":[1,2]}Cope with text that might not be JSON:
set data to nullset data to mash.json.decode("not json")error printline "Bad JSON: {{mash.error.message}}" set data to {}endprintline count(data)Bad JSON: json decode - check your input0Watch out for
Section titled “Watch out for”- A missing key is
null. Use??for a default:data["phone"] ?? "none". - Very large whole numbers lose digits.
12345678901234567890is written as1.2345678901234567e+19. Keep ids and amounts you must not lose as text. - An empty dictionary is written as
[].mash.json.encode({})gives[], not{}. A service that insists on{}needs it built as text. - Empty
{}and empty[]both decode to an empty collection. If it matters which one a service gave you, don’t rely on the shape.
See also
Section titled “See also”Talking to the outside world, and mash.http, whose responses carry a json property.
Methods
Section titled “Methods”decode
Section titled “decode”json.decode(string: string, associative?: bool = true)
Decode a JSON string into an array or object
encode
Section titled “encode”json.encode(mixed: mixed) → string
Encode a value as a JSON string