Expand/Shrink

parse_json

Definition: include builtins\json.e
object res = parse_json(string s)
Description: Converts a string representation of a JSON object into an internal form suitable for further processing.

s: should contain a valid string representation of a JSON object.
pwa/p2js: Supported.
Notes: The result of parsing a JSON string is as follows:
  • Numbers and Strings (without quotes) are held natively
  • An object is held as a sequence with a first element of -1 (JSON_OBJECT), and the rest pairs, the first of which is a string and the second any of these types.
  • An array is held as a sequence with a first element of -2 (JSON_ARRAY), and the rest any of these types.
  • A keyword is held as a sequence with a first element of -3 (JSON_KEYWORD), and one of the strings "true", "false", or "null".
Note the subscript of the first pair in an object, and element in an array, is always [2].

For some more valid (and invalid) JSON examples, see demo\rosetta\JSON.exw.

Attempts to parse an invalid JSON string yield {JSON_INVALID}, ie {-4}.
Example 1:
include builtins\json.e
string str = `{"this":"that","age":29}`
object res = parse_json(str)
-- res is {JSON_OBJECT,{"this","that"},{"age",29}}
(Although that might look like it hasn’t achieved much, the input is a single string of 24 characters, but there are 3 separate strings in the output, and str[22..23] is the string "29" whereas res[3][2] is the integer 29.)
Example 2:
-- note that parse_json() is non-thread-safe, 
--  without suitable protection such as the following:
include builtins\json.e
...
integer json = init_cs()
...
enter_cs(json)
res = parse_json(src)
leave_cs(json)
See Also: print_json