json_stringify

This function converts a single struct or a hierarchy of nested structs and arrays into a valid JSON string.

You supply the initial value to use (a Struct or an Array) and then the function will "stringify" it, i.e. convert it into a JSON string (converting GameMaker arrays into JSON arrays, and GameMaker structs into JSON objects). You can optionally choose to "prettify" it, meaning the final JSON will be formatted for easy readability.

Usage Notes

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

过滤功能 可选

该函数可以选择采用 Function,该函数对结构中的每个值运行一次,包括所有嵌套结构 / 数组及其内部的所有值。

它需要两个参数 (key, value),其中 key 是结构体键名称 (String) 或数组索引 (Real), 是存储在该键 / 索引中的内容。

The filter function must always return a value. It can return a new value, which replaces the key's value in the final converted format returned by json_stringify. If no new value should be returned for a particular key, the function must return the original value.

注意 在过滤器函数中覆盖键的值 (使用 return) 时,请确保首先检查其类型,因为过滤器函数也会针对根结构和任何嵌套结构运行,这意味着意外覆盖它们将导致最终结构损坏。请参阅底部的 示例 3

 

语法:

json_stringify(val, [pretty_print], [filter_func]);

参数类型描述
valStruct or Array要转换为 JSON 字符串的结构或数组的引用值
prettifyBoolean可选 Whether to prettify the string, i.e. insert indentation and line breaks for readability
filter_funcFunction可选 处理每个项目的过滤器函数。语法: function(key, value) -> new_value

 

返回:

String

 

示例1:

var _contents =
{
    version : "1.0.0",
    data:
    {
        coins : 4,
        mana : 15,
        playername : "Gurpreet",
        items :
        [
            ITEM.SWORD,
            ITEM.BOW,
            ITEM.GUITAR
        ]
    }
};

var _json_string = json_stringify(_contents);

上面的代码会将 _contents 结构转换为 JSON 字符串并将该字符串存储在一个变量中。 返回的字符串如下所示:

{ "data": { "items": [ 0.0, 1.0, 2.0 ], "coins": 4.0, "mana": 15.0, "playername": "Gurpreet" }, "version": "1.0.0" }

 

示例2:美化输出

var _contents = 
{
    version: "1.0.0",
    data:
    {
        coins : 5,
        mana : 0,
        playername : "Bart",
        items :
        [
            ITEM.SWORD,
            ITEM.BOW,
            ITEM.PIANO
        ]
    }
}
var _json_string = json_stringify(_contents, true);

上面的代码将 _contents 结构转换为 JSON 字符串并将其存储在变量中。当 pretty_print 参数设置为 true 时,结构的内容将被美化输出到字符串中,即插入缩进和换行符,以使结果字符串看起来"漂亮"且更具可读性。然后,字符串看起来如下所示:

{
  "data":{
    "mana":0.0,
    "playername":"Bart",
    "items":[
      0,
      1,
      2
    ],
    "coins":5.0
  },
  "version":"1.0.0"
}

 

Example 3: Filter Function

var data =
{
    x: 5.2344,
    y: 10.601,
    last_clicked: undefined,
    values :  [ 2000.1, 30.56, undefined, { slot : 10, skin : undefined } ]
}

var json = json_stringify(data, true, function(key, value)
{
    if (is_real(value)) return round(value);
    if (is_undefined(value)) return 0;
    return value;
});

show_debug_message(json);

上面的代码采用一个结构并将其字符串化为 JSON,漂亮地打印它,并使用过滤器函数来修改某些类型的值。

如果该值是 Real,则对其进行 舍入 ; 如果是 未定义 ,则将其更改为 0,否则仅返回相同的值 (意味着它保持不变)。