SML# Document Version 4.0.0
13 SML# feature: dynamic types and typed manipulation of JSON

13.5 Language constructs for JSON manipulation

SML# provides the following constructs:

  • Importing a JSON data.

    Dynamic.fromJson : string -> Dynamic.void Dynamic.dyn

    This function parses a JSON string and read it as a partially dynamic record. It raises the Dynamic.RuntimeTypeError exception if the parsing failed. In the return type, Dynamic.void denotes that the structure of the value is not yet statically known.

  • Dynamic type checking expression _dynamic exp as τ and dynamic patttern matching expression _dynamiccase. These expressions described in Section 13.1 are also useful for JSON type checking. The following types are allowed as τ:

    • Ordinary ML types such as basic types such as int, bool, and string; record types; list types; and arbitrary combination of these. Only if the structure of the given JSON matches with τ completely, the type cast succeeds.

    • Partially dynamic record types of the form {l1:τ1, , ln:τn} Dynamic.dyn. Only if the given JSON is a object that have at least labels l1,,ln and the value of each label li can be casted to τi, then the type cast succeeds.

    • Completely dynamic type Dynamic.void Dynamic.dyn. The type cast to this type always succeeds.

    • Arbitrary nested combination of the above types.

  • Obtaining a static view.

    Dynamic.view : [’a#reify. ’a Dynamic.dyn -> ’a]

    This function converts the statically known part of the given partially dynamic record to its corresponding ML data structure. It raises the Dynamic.RuntimeTypeError exception if the argument is of type Dynamic.void Dynamic.dyn.

  • JSON printer.

    Dynamic.toJson : [’a. ’a Dynamic.dyn -> string]

    This function returns the string representation of the given JSON. The result includes all fields in the given JSON regardless of the type instance of ’a.

As seen in the type of JSON data, it is allowed to use functions for dynamically-typed values and reification with JSON data. Conversely, it is also allowed to apply these functions for partially dynamic records to dynamically-typed values.