Dlang JSON 序列化和反序列化:对应 PHP json_encode 和 json_decode 函数
以下是对应 PHP 中 json_encode 和 json_decode 函数的 Dlang 语言实现:
- json_encode 函数:
import std.json;
void main()
{
auto data = ['name':'John', 'age':30, 'city':'New York'];
auto jsonString = data.jsonStringify;
writeln(jsonString); //输出:{"name":"John","age":30,"city":"New York"}
}
- json_decode 函数:
import std.json;
void main()
{
auto jsonString = `{"name":"John","age":30,"city":"New York"}`;
auto data = jsonString.jsonParse;
writeln(data['name']); //输出:John
writeln(data['age']); //输出:30
writeln(data['city']); //输出:New York
}
- 从文件中读取 JSON 数据并解析:
import std.json;
import std.stdio;
void main()
{
auto file = File("data.json", "r");
auto jsonString = file.readText();
file.close();
auto data = jsonString.jsonParse;
writeln(data); //输出解析后的 JSON 数据
}
原文地址: https://www.cveoy.top/t/topic/oekp 著作权归作者所有。请勿转载和采集!