json_encode

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:

json_encode takes a DS map that you have previously created and encodes it as a JSON string which you can then use as (for example) part of an http_post_string() call, or - so it can be stored externally - it can be written to a file. Note that care should be taken when writing JSON to an ini file, as the ini specifications can cause issues when using quotes and escape characters. See the function ini_write_string() for more information. Also note that if you encode an int64 to JSON it will write it as an int if it is in the valid range for an int32, as a double if it can do so without losing precision or (if neither of those cases is applicable) as a string with an identifier "@i64@" before it and "$i64$" after it. When you come to decode the JSON to a map again GameMaker Studio 2 will pick these identifiers up and re-convert the value to an int64.

NOTE: The hierarchal functionality of JSON is available through special DS map and DS list functions, so you are able to encode sub-lists and maps.

 

Syntax:

json_encode(map)

Argument Description
map a ds_map with the information to encode

 

Returns:

string

 

Example:

var hiscore_map, i, str;
hiscore_map = ds_map_create();
for (i = 0; i < 10; i ++;)
    {
    ds_map_add(hiscore_map, name[i], score[i]);
    }
str = json_encode(hiscore_map);
get[0] = http_post_string("http://www.angusgames.com/game?game_id=" + string(global.game_id), str)
ds_map_destroy(hiscore_map);

The above code creates a DS map and then loops through the name and score arrays, adding each key/value pair to the new map. Next, this map is encoded using json_encode() and stored as a string in the variable "str". This string is then sent to a web server using http_post_string() and the DS map is destroyed to prevent a memory leak as it is no-longer needed.