javascript - 修复无效 JSON 的最有效方法

标签 javascript c# json .net-4.0 fastjson

我陷入了一个不可能的境地。我有一个来自外太空的 JSON(他们无法更改它)。这是 JSON

{
    user:'180111',
    title:'I\'m sure "E pluribus unum" means \'Out of Many, One.\' \n\nhttp://en.wikipedia.org/wiki/E_pluribus_unum.\n\n\'',
    date:'2007/01/10 19:48:38',
    "id":"3322121",
    "previd":112211,
    "body":"\'You\' can \"read\" more here [url=http:\/\/en.wikipedia.org\/?search=E_pluribus_unum]E pluribus unum[\/url]'s. Cheers \\*/ :\/",
    "from":"112221",
    "username":"mikethunder",
    "creationdate":"2007\/01\/10 14:04:49"
}

“它远不是有效的 JSON”,我说。他们的回答是“嗯!但是 Javascript 可以毫无怨言地阅读它”:

<html>
<script type="text/javascript">
    var obj = {"PUT JSON FROM UP THERE HERE"};

    document.write(obj.title);
    document.write("<br />");
    document.write(obj.creationdate + " " + obj.date);
    document.write("<br />");
    document.write(obj.body);
    document.write("<br />");
</script>
<body>
</body>
</html>

问题

我应该通过 .NET(4) 读取和解析这个字符串,它破坏了 Json.org 的 C# 部分中提到的 14 个库中的 3 个。 (没有尝试其余的)。为了解决问题,我编写了以下函数来解决单引号和双引号的问题。

public static string JSONBeautify(string InStr){
    bool inSingleQuote = false;
    bool inDoubleQuote = false;
    bool escaped = false;

    StringBuilder sb = new StringBuilder(InStr);
    sb = sb.Replace("`", "<°)))><"); // replace all instances of "grave accent" to "fish" so we can use that mark later. 
                                        // Hopefully there is no "fish" in our JSON
    for (int i = 0; i < sb.Length; i++) {
        switch (sb[i]) {

            case '\\':
                if (!escaped)
                    escaped = true;
                else 
                    escaped = false;
                break;
            case '\'':
                if (!inSingleQuote && !inDoubleQuote) {
                    sb[i] = '"';            // Change opening single quote string markers to double qoute
                    inSingleQuote = true;
                } else if (inSingleQuote && !escaped) {
                    sb[i] = '"';            // Change closing single quote string markers to double qoute
                    inSingleQuote = false;
                } else if (escaped) {
                    escaped = false;
                }
                break;
            case '"':
                if (!inSingleQuote && !inDoubleQuote) {
                    inDoubleQuote = true;   // This is a opening double quote string marker
                } else if (inSingleQuote && !escaped) {
                    sb[i] = '`';            // Change unescaped double qoute to grave accent
                } else if (inDoubleQuote && !escaped) {
                    inDoubleQuote = false; // This is a closing double quote string marker
                } else if (escaped) {
                    escaped = false;
                }
                break;
            default:
                escaped = false;
                break;
        }
    }
    return sb.ToString()
        .Replace("\\/", "/")        // Remove all instances of escaped / (\/) .hopefully no smileys in string
        .Replace("`", "\\\"")       // Change all "grave accent"s to escaped double quote \"
        .Replace("<°)))><", "`")   // change all fishes back to "grave accent"
        .Replace("\\'","'");        // change all escaped single quotes to just single quote
}

现在 JSONlint 只会提示属性名称,我可以使用 JSON.NET 和 SimpleJSON 库来解析以上 JSON。

问题

我确信我的代码不是修复上述 JSON 的最佳方式。 是否存在我的代码可能会中断的情况?有更好的方法吗?

最佳答案

您需要通过 JavaScript 运行它。在 .net 中启动 JavaScript 解析器。将字符串作为 JavaScript 的输入并使用 JavaScript 的原生 JSON.stringify 进行转换:

obj = {
    "user":'180111',
    "title":'I\'m sure "E pluribus unum" means \'Out of Many, One.\' \n\nhttp://en.wikipedia.org/wiki/E_pluribus_unum.\n\n',
    "date":'2007/01/10 19:48:38',
    "id":"3322121",
    "previd":"112211",
    "body":"\'You\' can \"read\" more here [url=http:\/\/en.wikipedia.org\/?search=E_pluribus_unum]E pluribus unum[\/url]'s. Cheers \\*/ :\/",
    "from":"112221",
    "username":"mikethunder",
    "creationdate":"2007\/01\/10 14:04:49"
}

console.log(JSON.stringify(obj));
document.write(JSON.stringify(obj));

请记住,您获得的字符串(或对象)不是有效的 JSON,并且无法使用 JSON 库进行解析。它需要先转换为有效的 JSON。但是它是有效的 JavaScript。

要完成这个答案:您可以在 .Net 中使用 JavaScriptSerializer。对于此解决方案,您需要以下程序集:

  • System.Net
  • 系统.Web.Script.序列化

    var webClient = new WebClient();
    string readHtml = webClient.DownloadString("uri to your source (extraterrestrial)");
    var a = new JavaScriptSerializer();
    
    Dictionary<string, object> results = a.Deserialize<Dictionary<string, object>>(readHtml);
    

关于javascript - 修复无效 JSON 的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28383478/

相关文章:

c# - 我们什么时候需要IOptions?

c# - expression.bind 和 expression.assign 之间有什么区别(或 : what is special about MemberBinding)

c# - 在 numericupdown 控件中显示前导零 (C#)

javascript - 显示 GeoJson 文件中的一个 map 标记

javascript - 如何从地理编码器中仅获取城市名称?

javascript - 在信息窗口中嵌入街景图片 - Googlemaps v3

javascript - 如何让 Firefox 将 XML namespace 附加到我的 html 元素?

json - 您应该如何引用 JSON 对象符合的 JSON 模式?

json - 如何在swift中处理不同的JSON HTTP响应

javascript - 火狐插件 : quit-application observer not working