json_parse

This function can be used to parse a JSON string (either previously created using json_stringify or from any valid source), and convert it into a collection of arrays or structs, where an array is the equivalent of a JSON array and a struct is the equivalent of a JSON object. You supply the string to parse, and the function will return the top level array or struct which can then be checked in your code. If you are not sure of the contents of the JSON, you can use the different Variable Functions (like typeof() or variable_struct_get_names()) to check the returned contents. Note that trying to parse an invalid value (ie: not a string) will throw an exception error.

If the supplied JSON string includes "undefined" as a value for any property, it will be converted to pointer_null upon being parsed.

 

Syntax:

json_parse(json)

Argument Description
json The JSON to parse (a string)

 

Returns:

Nested structs and arrays

 

Extended Example:

In this example we will parse the following JSON string which we'll hold in the variable "json":

json = "{\"myObj\": { \"apples\":10, \"oranges\":12, \"potatoes\":100000, \"avocados\":0 }, \"myArray\":[0, 1, 2, 2, 4, 0, 1, 5, 1]}"

This string would be parsed something like this:

data = json_parse(json);
if variable_struct_exists(data, "myObj")
{
if is_struct(data.myObj)
    {
    var _names = variable_struct_get_names(data.myObj);
    var _str = "";
    for (var i = 0; i < array_length(_names); i++;)
        {
        _str = _names[i] + ": " + string(variable_struct_get(data.myObj, _names[i]));
        show_debug_message(_str);
        }
    }
if variable_struct_exists(data, "myArray")
    {
    if is_array(data.myArray)
        {
        show_debug_message(data.myArray);
        }
    }
}

The above code will parse the given JSON string, generating the following console output:

oranges: 12
potatoes: 100000
avocados: 0
apples: 10
[ 0,1,2,2,4,0,1,5,1 ]