Expand/Shrink

extract_json_field

Definition: include builtins\json.e
object res = extract_json_field(sequence json_object, string string name, object object dflt="?9/0")
Description: Retrieves a named field from a JSON_OBJECT.

json_object: must be a valid JSON_OBJECT.
name: the name of the element to retrieve.
dflt: the value to return if the field is not found.
pwa/p2js: Supported.
Notes: A fatal error occurs if json_object is not a sequence or json_object[1]!=JSON_OBJECT.

The result may be a number, a string, a JSON_OBJECT, a JSON_ARRAY, a JSON_KEYWORD, or the value in dflt.

If dlft is not overidden, a fatal error occurs if the field is not found (which is useful to trap typos), but of course you can specify any value such as 0, -1, "??", or {} - pick something not likely to be confused with anything in the actual data - the best choice probably being {}, since the equivalents of that from parse_json() are typically {JSON_OBJECT} ("{}") or {JSON_ARRAY} ("[]").
Example:
include builtins\json.e
string str = `{"this":"that","age":29}`
object res = parse_json(str)
if res={JSON_INVALID} then
    ?"error: invalid json"
elsif sequence(res) and res[1]=JSON_OBJECT then
    ?extract_json_field(res,"this") -- "that"
    ?extract_json_field(res,"age")  -- 29
else
    ?res -- ???
end if
See Also: parse_json