我正在寻找一个函数,该函数将 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;
最佳答案
如果您不想使用任何外部库,并且您使用的是 delphi XE5 或更新版本,那么 REST 中有一个非常方便的
单位。TJson.Format()
函数。 Json
uses json, REST.Json;
{ ... }
function FormatJSON(json: String): String;
var
tmpJson: TJsonObject;
begin
tmpJson := TJSONObject.ParseJSONValue(json);
Result := TJson.Format(tmpJson);
FreeAndNil(tmpJson);
end;
https://stackoverflow.com/questions/18511333/