【发布时间】:2013-08-29 12:42:44
【问题描述】:
我正在寻找一个函数,该函数将 JSON 字符串作为输入并使用换行符和缩进(制表符)对其进行格式化。
示例: 我有输入线:
{"menu": {"header": "JSON viewer", "items": [{"id": "Delphi"},{"id": "Pascal", "label": "Nice tree format"}, null]}}
并希望得到一个可读的文本结果:
{
"menu":{
"header":"JSON viewer",
"items":[
{
"id":"Delphi"
},
{
"id":"Pascal",
"label":"Nice tree format"
},
null
]
}
}
我找到了很多 PHP 和 C# 的示例,但不是 Delphi。 有人可以帮忙实现这样的功能吗?
更新 - 使用 SuperObject 的解决方案:
function FormatJson (InString: WideString): string; // Input string is "InString"
var
Json : ISuperObject;
begin
Json := TSuperObject.ParseString(PWideChar(InString), True);
Result := Json.AsJson(true, false); //Here comes your result: pretty-print JSON
end;
【问题讨论】:
-
很高兴分享答案。
-
如果您只是将输入参数类型更改为
WideString,则不需要任何该转换代码;每当您调用FormatJson时,编译器都会自动执行等效任务。只需更改类型,即可将前七行替换为Json := TSuperObject.ParseString(PWideChar(InString), True)。
标签: json delphi formatting pascal pretty-print