我正在尝试将 JSON 字符串转换为可用于在 Lisp (aml) 中进行评估的字符串格式。
我想转换 f.eks.:
{“id”:1,“名称”:“Foo”,“价格”:123,“标签”:[“Bar”,“Eek”],“库存”:{“仓库”:300,“零售”: 20} }
至:
(json-object (json-object-property "id" <1>) (json-object-property "name" <"Foo">) (json-object-property "price" <123>) (json-object-property "tags"(json-array (list "Bar" "Eek")) (json-object-property "stock"(json-object (json-object-property "warehouse" <300>) (json-object-property "retail" <20>)))))
我首先尝试使用 C# 和 Regex 来执行此操作,然后将其“翻译”为 lisp/aml。所以我的问题是:
如何在 C# 中使用正则表达式来做到这一点?我已经尝试了很多,但总是以包含非单词字符或很少“(”的字符串而告终。
我以前从未使用过正则表达式,所以代码看起来不太聪明:
string input = @"{""id"": 1,""name"": ""Foo"",""price"": 123,""tags"": [""Bar"",""Eek""],""stock"": {""warehouse"": 300,""retail"": 20}}""";
string pattern = @"[}]";
string replacement = ")";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
pattern = @"((?<word1>""\w+"")(:\s)(?<word2>""\w+""|\d+))";
replacement = @"(json-object-property ${word1} <${word2}>)";
rgx = new Regex(pattern);
result = rgx.Replace(result, replacement);
pattern = @"[]]";
replacement = "))";
rgx = new Regex(pattern);
result = rgx.Replace(result, replacement);
pattern = @"[{]";
replacement = "(json-object ";
rgx = new Regex(pattern);
result = rgx.Replace(result, replacement);
pattern = @"[[]";
replacement = "(json-array (list ";
rgx = new Regex(pattern);
result = rgx.Replace(result, replacement);
pattern = @"[,]";
replacement = " ";
rgx = new Regex(pattern);
result = rgx.Replace(result, replacement);
pattern = @"(?<word1>""\w+"")(:\s)";
replacement = @"(json-object-property ${word1}";
rgx = new Regex(pattern);
result = rgx.Replace(result, replacement);
Console.WriteLine(result);