Repository navigation
JSON
脚本里存的数据活到脚本结束就没了。如果要把数据保存到文件,或者通过网络传输,就需要一种"文本格式"来表示。JSON 是最常见的这种格式。
Data in a script is gone once the script ends. To save data to a file or send it over the network, a text format is needed. JSON is the most common one.
HimDSL 提供两个内置函数:
HimDSL offers two built-ins:
-
toJson(x)—— 把容器或值转成 JSON 字符串。 -
fromJson(s)—— 把 JSON 字符串还原成容器或值。 -
toJson(x)— turn a container or value into a JSON string. -
fromJson(s)— turn a JSON string back into a container or value.
toJson 接收一个值,返回它的 JSON 文本表示。
toJson takes a value and returns its JSON text representation.
var m = map();
m.put("name", "Steve");
m.put("level", 30);
m.put("vip", true);
string json = toJson(m);
// {"name":"Steve","level":30,"vip":true}
支持的类型:
Supported types:
-
数字、布尔、字符串 → JSON 标量。
-
map→ JSON 对象。 -
vector、set、数组 → JSON 数组。 -
null→null。 -
Numbers, booleans, strings → JSON scalars.
-
map→ JSON object. -
vector,set, array → JSON array. -
null→null.
嵌套结构也能处理:
Nested structures work too:
var player = map();
player.put("name", "Steve");
player.put("pos", {100, 64, 200});
player.put("tags", {"vip", "staff"});
string json = toJson(player);
// {"name":"Steve","pos":[100,64,200],"tags":["vip","staff"]}
toJson 不会把自定义结构体、EntityRef、GUI 等复杂对象自动转成 JSON。它们会被当作字符串处理,通常不是你想要的结果。只对容器、数字、字符串、布尔使用 toJson。
toJson does not serialize custom structs, EntityRef, or GUI objects. They get stringified, usually not what you want. Use toJson on containers, numbers, strings, and booleans only.
fromJson 接收一个 JSON 字符串,返回解析出来的值:
fromJson takes a JSON string and returns the parsed value:
string json = "{\"name\":\"Steve\",\"level\":30}";
var data = fromJson(json);
string name = data.get("name"); // "Steve"
int level = data.get("level"); // 30
JSON 对象还原为 map,JSON 数组还原为 vector。标量直接还原为对应类型。
JSON objects become map, JSON arrays become vector, scalars become their native types.
string arrJson = "[1, 2, 3, 4]";
var arr = fromJson(arrJson);
int first = arr.get(0); // 1
int total = arr.size(); // 4
如果字符串不是合法 JSON,fromJson 会抛出错误,中断脚本执行。所以从外部读入 JSON 时先确认格式:
If the string is not valid JSON, fromJson throws and aborts the script. Validate before parsing external input:
string text = freadlines("data.json").get(0);
if (text.startsWith("{")) {
var data = fromJson(text);
// ...
}
(freadlines 的用法见文件 I/O 章节。)
把玩家数据保存到文件:
Save player data to a file:
int main() {
var data = map();
data.put("name", "Steve");
data.put("level", 30);
data.put("vip", true);
data.put("tags", {"vip", "staff"});
string json = toJson(data);
fwritelines("player_data.json", {json});
runcmd("CONSOLE", "say 已保存");
}
读取回来:
Load back:
int main() {
if (!fexists("player_data.json")) {
runcmd("CONSOLE", "say 文件不存在");
return;
}
var lines = freadlines("player_data.json");
if (lines.size() == 0) return;
string json = lines.get(0);
var data = fromJson(json);
string name = data.get("name");
int level = data.get("level");
runcmd("CONSOLE", "say " + name + " 等级 " + level);
}
var list = vector();
var p1 = map();
p1.put("name", "Steve");
p1.put("level", 30);
list.add(p1);
var p2 = map();
p2.put("name", "Alex");
p2.put("level", 25);
list.add(p2);
string json = toJson(list);
fwritelines("players.json", {json});
// [{"name":"Steve","level":30},{"name":"Alex","level":25}]
string json = freadlines("players.json").get(0);
var list = fromJson(json);
for (int i = 0; i < list.size(); i = i + 1) {
var item = list.get(i);
string name = item.get("name");
int level = item.get("level");
runcmd("CONSOLE", "say " + name + ":" + level);
}
fromJson 解析整数时,会尽量返回 int;超出范围则返回更大的数值类型:
When parsing integers, fromJson prefers int; out of range, a larger numeric type is returned:
var a = fromJson("42"); // int 42
var b = fromJson("3.14"); // double 3.14
从 JSON 读出来的数字,实际类型未必是 int。需要确定类型时,显式转换:
Numbers read from JSON may not be int. Convert explicitly when the type matters:
int level = toInt(data.get("level"));
如果你手写 JSON 字符串,双引号要转义:
If you write JSON by hand, double quotes must be escaped:
string json = "{\"key\":\"value\"}"; // ✓ 字符串里转义
更好的方式是用 toJson 从容器生成,避免手写 JSON。
Better: use toJson on a container and avoid hand-writing JSON.
var m = map();
m.put("key", "value");
string json = toJson(m); // ✓ 自动处理
var data = fromJson(text);
int x = data.get("x"); // 可能报错,如果解析出的是 double
显式转换:
Convert explicitly:
int x = toInt(data.get("x"));
var arr = fromJson("[1, 2, 3]");
string s = arr.get(0); // ✗ 拿到的是数字,不是字符串
读到值之后,用显式的 toInt / toString 转成需要的类型。
After reading a value, convert to the desired type with toInt / toString.
Escape double quotes, or generate JSON with toJson.
Convert explicitly.
Convert to the needed type.
-
toJson(x)把容器/标量转成 JSON 字符串。 -
fromJson(s)把 JSON 字符串还原为map、vector或标量。 -
只对容器、数字、字符串、布尔使用,不要传结构体或对象。
-
解析失败会中断脚本,外部数据先校验。
-
从 JSON 读出的数字类型不一定,按需
toInt/toDouble。 -
生成 JSON 用
toJson,不要手写。 -
toJson(x)turns a container/scalar into a JSON string. -
fromJson(s)restores amap,vector, or scalar. -
Use only on containers, numbers, strings, booleans.
-
Parse failure aborts; validate external data.
-
Numbers from JSON are not always
int; convert as needed. -
Generate with
toJson, do not hand-write.
数据结构部分到此结束。四章覆盖了:固定长度数组、三种通用容器、两种顺序容器、以及 JSON 序列化。选择原则:数量固定用数组;需要动态大小用 vector;去重用 set;按键查值用 map;先入先出用 queue;后入先出用 stack。默认用 vector,其他都是特殊情况。
The Data Structures section ends here. Four chapters covered: fixed-length arrays, three general containers, two order-specific containers, and JSON. Selection rule: fixed count → array; dynamic → vector; uniqueness → set; key lookup → map; FIFO → queue; LIFO → stack. Default to vector; the others are special cases.
下一部分进入自定义类型。第十章 [struct 结构体 / Structs] 介绍把多个字段打包成一个整体。
The next part covers custom types. Chapter [struct 结构体 / Structs] packages multiple fields into one unit.
- 首页 / Home
- 安装与快速开始 / Installation & Quick Start
- 第一个脚本 / Your First Script
- 命令速查 / Command Reference
- 自动执行脚本 / Auto-run Scripts
- 定义函数 / Defining Functions
- 函数重载 / Function Overloading
- Lambda 表达式 / Lambda Expressions
- 函数式接口 / Functional Interfaces
- 选择器总览 / Selectors Overview
- 选择器过滤器 / Selector Filters
- EntityRef 引用 / EntityRef
- 占位符参考 / Placeholders Reference
- PlaceholderAPI 桥接 / PAPI Bridge
- 创建 GUI / Creating a GUI
- GUISlot 槽位 / GUISlot
- 点击回调 / Click Callbacks
- onClose 回调 / onClose Callback
- GUI 刷新 / GUI Refresh
- 数学函数 / Math Built-ins
- 高精度计算 / BigDecimal Built-ins
- 字符串函数 / String Built-ins
- 集合函数 / Collection Built-ins
- 文件 I/O / File I/O
- 命令与 sleep / Commands & sleep