json_decode


Description

JSON (JavaScript Object Notation) is a lightweight data-interchange format which is easy for to read and write, for both people and machines. It is built on two basic structures:

With this function, you can decode a piece of JSON and convert it into a ds_map, ready for use in GameMaker Studio 2. If the JSON to be decoded requires a hierarchy of lists and maps within the central ds_map, these are decoded too and also created for you, using the following rules (note that these rules apply to the top-level structure only):

NOTE: When decoding arrays, there is a map with the key "default" ONLY when an array is the top level structure, and ONLY for that top-level array. Internal lists decode directly to ds_lists without being enclosed in a ds_map.


Normally you would know what keys the JSON decodes to, but if not then you can use the ds_map_size, ds_map_find_first and ds_map_find_next functions to parse the map and get the necessary information.

NOTE: GameMaker Studio 2 creates the necessary ds_maps and lists from the JSON, and for cleaning up you only need to delete the top level map or list and GameMaker Studio 2 will automatically delete from memory all the maps and lists underneath.


Syntax:

json_decode(string)


Argument Description
string The JSON format string that you are passing to the function for decoding


Returns:

ds_map id or -1 if it fails


Example:

var resultMap = json_decode(requestResult);
var list = ds_map_find_value(resultMap, "default");
var size = ds_list_size(list);
for (var n = 0; n < ds_list_size(list); n++;)
   {
   var map = ds_list_find_value(list, n);
   var curr = ds_map_find_first(map);
   while (is_string(curr))
      {
      global.Name[n] = ds_map_find_value(map, "name");
      curr = ds_map_find_next(map, curr);
      }
   }
ds_map_destroy(resultMap);

The above code will decode a JSON string and parse it to generate a global array.