Skip to main content

JSONParser

Latest Version: 1.0.0

This library parses JSON into Squirrel data types.

You can view the library’s source code on GitHub. Click here to see information on the available versions of this library.

To add this library to your project, add #require "JSONParser.class.nut:1.0.0" to the top of your agent and/or device code.

Usage

JSONParser has no constructor and one public function, parse().

parse(jsonString[, converterFunction])

The parse() method takes one required parameter, a JSON encoded string, and one optional parameter: a function used to convert custom types. The method returns a deserialized version of the object that was passed in.

Basic Example

local jsonString = "{\"one\" : 1}";
result <- JSONParser.parse(jsonString);
server.log(result.one);
// Displays '1'

Custom Types Converter

The optional converter function can be used to deserialize custom types. It takes two parameters:

  • value — String representation of a value
  • type — String indicating conversion type: "string" or "number"

For example, the following code converts all numbers to floats and makes strings uppercase:

result <- JSONParser.parse(jsonString, function (value, type) {
  if (type == "number") {
    return val.tofloat();
  } else if (type == "string") {
    return val.toupper();
  }
});

Extended Example

class MyCustomType {
  _value = null;

 constructor(value) {
    this._value = value;
  }

  function _serialize() {
    return "@mycustomtype:" + this._value;
  }

  function getValue() {
    return this._value;
  }
}

o <- {a = 1, b = "Something", c = MyCustomType("100500") };
s <- JSONEncoder.encode(o);

server.log(s);
// Displays '{"a":1,"c":"@mycustomtype:100500","b":"Something"}'

result <- JSONParser.parse(s, function (val, type) {
  if ("number" == type) {
    return val.tofloat();
  } else if ("string" == type) {
    if (null != val.find("@mycustomtype")) {
      // Convert my custom type
      val = MyCustomType(val.slice(14))
    }

    return val;
  }
});

server.log(result.c instanceof MyCustomType);
// Displays 'true'

server.log(result.c.getValue());
// Displays '100500'

Release History

The Electric Imp Dev Center documents the latest version of the library. For past versions, please see the Electric Imp public GitHub repos listed below.

Version Source Code Notes
1.0.0 GitHub Initial release

License

The JSONParser class is licensed under MIT License.