JSON

Parsing JSON text into objects; use string() for the reverse.

JSON.parse() converts JSON text (from http responses, MQTT messages or files) into script objects. The reverse — serialising an object to JSON text — is done with the global string() function.

Functions

JSON.parse()

JSON.parse(text) → object

Parses a JSON string into an object.

Arguments

NameTypeRequiredDefaultDescription
text string yes JSON text, e.g. res.payload from http.req or event.message from MQTT.

Returns

object The parsed value.

Example

let res = http.req(url, string(request), 1000, false);
if(res.err === 0 && res.code === 200){
  let payload = JSON.parse(res.payload);
  print("Remote Q5 Battery Voltage", payload.batteryVoltage);
}

JSON.stringify()

JSON.stringify(value) → string

Serialises a value to JSON text — equivalent to the global string() for objects.

Available per the mJS standard. In the factory examples the global string() function is normally used for the same purpose.

Arguments

NameTypeRequiredDefaultDescription
value any yes The value to serialise.

Returns

string JSON text.

Example

let payload = JSON.stringify({ v: 14.3 }); // '{"v":14.3}'