json_encode

This function takes an existing DS Map and encodes it as a JSON string. The JSON string can be used, e.g., as part of an http_post_string call or be written to a file, so the data can be stored externally.

重要 This function - while still valid - has been superseded by the function json_stringify, and we recommend that you only use this function for legacy support.

The DS map can contain the following: 

Usage Notes

NOTE See Guide To Using JSON for detailed information on how to work with JSON in GameMaker.

语法:

json_encode(map, [prettify])

参数类型描述
mapDS MapA DS map with the information to encode
prettifyBoolean可选 Whether to prettify the output, i.e. insert indentation and line breaks for readability

 

返回:

String

 

示例1:基本使用

var _hiscore_map, _json;
_hiscore_map = ds_map_create();
for (var i = 0; i < 10; i ++;)
{
    ds_map_add(_hiscore_map, name[i], score[i]);
}
_json = json_encode(_hiscore_map);
ds_map_destroy(_hiscore_map);

post_request_id = http_post_string($"http://www.angusgames.com/game?game_id={global.game_id}", _json);

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.

 

Example 2: Hierarchy of Mixed Data Types

var _map = ds_map_create();
var _list = ds_list_create();

ds_map_add_list(_map, "seasoning", _list);
ds_list_add(_list, "pepper", "salt", "thyme");

_map[? "greeting"] = {parts: ["Hello", "World!"], separator: ", "};
_map[? "food"] = ["bread", "coconut", "mango"];

var _json = json_encode(_map, true);
// ds_map_destroy(_map);

show_debug_message(_json);

The code example above shows how to encode a DS map with mixed contents to JSON.

First, a DS map and a DS list are created and stored in temporary variables. The DS list is then added to the DS map using ds_map_add_list and gets a few items added to it with a call to ds_list_add. After that, two other keys are added to the map, one gets assigned a Struct as the value with an Array in it, the other gets assigned an array.

The map's contents are then encoded with a call json_encode, with the prettify parameter set to true. If you only need the JSON string, the map can be destroyed right after this.

Finally, the JSON string is shown in a debug message.