跳到主要内容

cjson

简介

json 序列化和反序列 使用开源库cjson, 来序列化和反序列化 gs 中的基本数据类型 与 gs 内置的 json 模块相比,

优点:

  • pkg 更加符合规范
  • 可以输出可读性字符串

缺点:

  • 不能读取带注释的 json 文件

组件接口

cjson.gs

函数原型函数作用
bool check(string str)检查传入的字符串是否是json格式的
mixed loads(string str)将传入字符串反序列为 json 数据格式
mixed load(string path)根据文件路径, 读取文件内容, 并反序列化 json 数据格式
string dumps(mixed val, bool minify = false)将 gs 基本数据结构(map, array, string, int) 以 json 的形式序列化为字符串
void dump(mixed val, string path, bool minify = false)将 gs 基本数据结构(map, array, string, int) 以 json 的形式序列化为字符串, 并保存到文件

示例

import pkg.cjson;

string path = "package.json"; //the path to json file

write(HIY, "the origin file:\n", NOR);
write(file.read_all(path), "\n");

// begin @cjson.loads
// using str to parse a json object
map json_1 = cjson.loads(file.read_all(path));
write(HIY, "the object after parsing:\n", NOR);
write(json_1);
// end

// begin @cjson.load
// using file path to parse a json object
map json_2 = cjson.load(path);
write(HIY, "the object after parsing:\n", NOR);
write(json_1);
// end

// begin @cjson.dumps
// save json to string
string str = cjson.dumps(json_1);
write(HIY, "the string after saving:\n", NOR);
write(str, "\n");
// end

// begin @cjson.dump
// save json to file
string target = "package.bak.json";
cjson.dump(json_1, target);
// end