【问题标题】:Python to C Sharp Regex pattern to repair jsonPython 到 C Sharp Regex 模式来修复 json
【发布时间】:2015-01-08 16:30:36
【问题描述】:

我有一个硬件设备,它通过带有 json 字符串的 http 进行控制,但已知它返回的 json 是无效的。在 Python 中,我可以修复它

response = """[
{text: "67239961", selected: "true", value: "67239961"}
];"""
p = re.compile('([a-zA-Z_]+):')
joined = "".join(response.splitlines())
stripped = joined.strip(';')
cleaned = p.sub(r'"\1":', stripped)
>> [{"text": "67239961", "selected": "true", "value": "67239961"}]

不过,我需要在 C Sharp 中执行此操作,并且对它的 Regex 实现不够熟悉。我试图直接将其移植为

string[] split = response.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
string joined = String.Join("", split);
string stripped = joined.Trim(';');
Regex re = new Regex(@"([a-zA-Z_]+):");
string cleaned = re.Replace(stripped, @"\1");
>> [{\1 "67239961", \1 "true", \1"67239961"}]

实现这一点的正确模式是什么?

编辑:修复是

string cleaned = re.Replace(stripped, @"""$1"":");

【问题讨论】:

  • 我对C#中的正则表达式不熟悉,但是你可以尝试使用$1而不是\1
  • 感谢您的评论,留下了文字,但删除了冒号。我也改成 Regex re = new Regex(@"\([a-zA-Z_]+\):");并且它保持与开始时相同的状态

标签: c# python regex json


【解决方案1】:

借助 Newtonsoft JSON 包,您不必求助于 RegEx。

Install-Package Newtonsoft.Json

然后在你的代码中:

var str = @"[
{text: ""67239961"", selected: ""true"", value: ""67239961""}
];";

var json = JsonConvert.DeserializeObject(response.Replace(";",string.Empty));
var clean = JsonConvert.SerializeObject(json);

结果将是:

[{"text":"67239961","selected":"true","value":"67239961"}]

如果您确实有开头和结尾的引号,请使用:

var json = JsonConvert.DeserializeObject(
    str.Replace(";",string.Empty).Replace("\"[","[").Replace("]\"","]"));

【讨论】:

    猜你喜欢
    • 2020-08-07
    • 1970-01-01
    • 2018-06-14
    • 2013-05-05
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    相关资源
    最近更新 更多