Skip to content

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.

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.

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-1
A

Write 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 null
set data to mash.json.decode("not json")
error
printline "Bad JSON: {{mash.error.message}}"
set data to {}
end
printline count(data)
Bad JSON: json decode - check your input
0
  • A missing key is null. Use ?? for a default: data["phone"] ?? "none".
  • Very large whole numbers lose digits. 12345678901234567890 is written as 1.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.

Talking to the outside world, and mash.http, whose responses carry a json property.

json.decode(string: string, associative?: bool = true)

Decode a JSON string into an array or object

json.encode(mixed: mixed) → string

Encode a value as a JSON string