Parse (Json function)

From m204wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Create an JSON object from serialized JSON (Json class)

[Introduced in Model 204 7.6]

This function parse serialized JSON data contained in a unicode string into a Json object tree.

Syntax

%json = [%(Json):]Parse( unicode) Throws JsonParseError

Syntax terms

%jsonJson object
[%(Json):] The optional class name in parentheses denotes a virtual constructor.
unicode A unicode string containing serialized JSON data.

Usage notes

  • As with all virtual or true constructors, it is usually not necessary to specify the %(json): before the Parse method. That is %json = %(json):parse(%jsonString) is equivalent to %json = parse(%jsonString).
  • If there are errors parsing the input string, a JsonParseError exception is thrown.
  • Unicode data is typically encoded either as UTF-8 or UTF-16 (the former much more common in English language apps) so would need to be converted to unicode before being parsed by the Parse method. This would be done by the Utf8ToUnicode and Utf16ToUnicode String functions. For example %json = parse(%browserData:utf8ToUnicode) coverts the browser data (presumably in a longstring) to unicode before parsing it with Parse.
  • The JsonParse Unicode function provides identical functionality to the parse method though is invoked differently (the method object is a unicode string and there ar no parameters).
  • The parse method can parse JSON that consists simply of a quoted string, number, or boolean value. In these cases, the resultant Json object tree has a single object with a string, number, or boolean underlying type. If the JSON data consists simply of the unquoted string null Parse simply returns a null.

Examples

The following example parses a JSON object and then displays the values of the items in the object:

b %json is object json %data is unicode %data = '{"Lee": "To Kill a Mockingbird",' - '"Faulkner": ["As I Lay Dying", "Absalom, Absalom", "The Sound and the Fury"],' - '"Hurston": ["Jonahs Gourd Vine (1934)", "Their Eyes Were Watching God"],' - '"Ellison": "Invisible Man"}' %json = parse(%data) printText {~=%json('Faulkner')(2)} printText {~=%json('Ellison')} printText {~=%json('Hurston')(1)} printText {~=%json('Lee')} end

This prints:

%json('Faulkner')(2)="Absalom, Absalom" %json('Ellison')="Invisible Man" %json('Hurston')(1)="Jonah's Gourd Vine (1934)" %json('Lee')="To Kill a Mockingbird"

See also