繁体   English   中英

使用Javascript解析格式错误的JSON

[英]Parsing malformed JSON with Javascript

我想使用Javascript解析此内容 数据如下所示:

{"ss":[["Thu","7:00","Final",,"BAL","19","ATL","20",,,"56808",,"PRE4","2015"],["Thu","7:00","Final",,"NO","10","GB","38",,,"56809",,"PRE4","2015"]]}

在线上的每个教程都教您如何使用Twitter解析JSON,但是我不太确定如何使用JSON解析。

我想在一个网站上进行设置,以查看NFL团队为一个有趣的项目获得的分数以及有关解析JSON的良好学习体验,因为我不太在乎Twitter的内容。

这可能吗? 有什么好的入门教程吗? 甚至一些起始代码?

一般来说,您可以使用JSON.parse来执行此操作。 但是,您拥有的代码片段似乎并不是严格有效的JSON(如此处所示: http : //jsfiddle.net/yK3Gf/ ,也可以通过此处的源JSON验证: http : //jsonlint.com/ )。

因此,您将需要手工解析它,或者获取nfl.com来修复其JSON。

作为替代方案,当使用eval()时,其JSON可以成功解析,因此您可以使用以下内容进行解析:

var parsedData = eval('(' + jsonData + ')');

...如下所示: http : //jsfiddle.net/yK3Gf/1/

尽管请注意,通常不赞成以这种方式解析JSON(尤其是当解析的数据是由第三方来源传递时),因为如果数据恰好在其中包含任何可执行代码,它将使您容易受到XSS攻击它。

我处于类似的位置-非javascript专家致力于一个有趣的项目,以使自己熟悉javascript,ajax和json。

我采取了三个不同的步骤来解决该问题。 我欢迎任何有关改进解决方案的反馈。

第一步是查询nfl网站以降低得分。 由于json的来源(nfl网站)与您的网站不同,因此您必须解决针对跨域查询的javascript安全约束。 我发现此stackoverflow链接是一个很好的参考。 我使用JSONP解决。 我使用http://whateverorigin.org/作为间接网站。

$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://www.nfl.com/liveupdate/scorestrip/scorestrip.json') + '&callback=?', handleQueryForScoresResult);

正如其他人指出的那样,nfl站点返回无效的json数据。 以下示例行说明了该问题:

[“ Sun”,“ 4:25”,“ Final”,“ TEN”,“ 7”,“ MIN”,“ 30” ,,“ 55571”,“ REG5”,“ 2012”]],

请注意,空数组元素值(重复的逗号之间没有数据)。 因此,在我的json回调函数中,我通过在调用jquery解析json数据之前向重复的逗号添加空字符串(两个双引号)来更正数据:

function handleQueryForScoresResult(data) {
    var jsonStr = data.contents;
    jsonStr = jsonStr.replace(/,,/g, ',"",');
    jsonStr = jsonStr.replace(/,,/g, ',"",');

    var scoresData = jQuery.parseJSON(jsonStr).ss;
    .
    .
    .
}

最后,我创建了GameScores对象来封装json数据。

function GameScore(scoreData) {
    this.scoreData = scoreData;
    scoreData[2] = scoreData[2].toLowerCase();
    scoreData[5] = parseInt(scoreData[5]);
    scoreData[7] = parseInt(scoreData[7]);
} 

function GameScore_getAwayTeam() { return this.scoreData[4]; }
function GameScore_getHomeTeam() { return this.scoreData[6]; } 
function GameScore_isFinal() { return this.scoreData[2]=="final"; }  
function GameScore_getHomeTeamScore() { return this.scoreData[7]; }
function GameScore_getAwayTeamScore() { return this.scoreData[5]; }
function GameScore_doesHomeTeamLead() { return this.scoreData[7]> this.scoreData[5]; }
function GameScore_doesAwayTeamLead() { return this.scoreData[5]> this.scoreData[7]; }
function GameScore_getWeekId() { return this.scoreData[12]; }

GameScore.prototype.getHomeTeam = GameScore_getHomeTeam;
GameScore.prototype.getAwayTeam = GameScore_getAwayTeam;
GameScore.prototype.isFinal = GameScore_isFinal;
GameScore.prototype.getHomeTeamScore = GameScore_getHomeTeamScore;
GameScore.prototype.getAwayTeamScore = GameScore_getAwayTeamScore;
GameScore.prototype.doesHomeTeamLead = GameScore_doesHomeTeamLead;
GameScore.prototype.doesAwayTeamLead = GameScore_doesAwayTeamLead;
GameScore.prototype.getWeekId = GameScore_getWeekId;

我只添加了一些访问器,因为我不需要大多数数据。 您的需求可能会有所不同。

对于这个特定的问题(JSON响应中数组中的空索引),我用前瞻性断言进行了正则表达式替换。 考虑到该请求包含XMLHttpRequest

request.responseText.replace(/,(?=,)/gm, ",\"\"")

这将打开,,,"",也将在工作的情况下有顺序多个逗号,所以,,,,"","", 之后可以使用JSON.parse()

格式错误的JSON可以由dirty-json NPM包(我是作者)来解析。

您可以在此处测试解析器的演示: https : //rmarcus.info/dirty-json

解析器将您原始问题中的JSON解释为等效于以下有效JSON:

{
    "ss": [
        [
            "Thu",
            "7:00",
            "Final",
            "BAL",
            "19",
            "ATL",
            "20",
            "56808",
            "PRE4",
            "2015"
        ],
        [
            "Thu",
            "7:00",
            "Final",
            "NO",
            "10",
            "GB",
            "38",
            "56809",
            "PRE4",
            "2015"
        ]
    ]
}

我们正在使用mootools之类的东西,但是您也可以使用普通的JavaScript来做到这一点: http : //www.json.org/js.html

您的主要问题是,根据RFC 4627,引入的JSON格式错误或无效。

您可以执行的操作是复制JSON数据并使用此工具http://www.freeformatter.com/json-formatter.html对其进行格式化

格式化后的版本可以使用jQuery ajax调用

$.ajax({
    url: "your-formatted.json",
    dataType: 'json',

    success: function (data) {

        for (var i = 0; i < data.ss.length; i++) {
            document.write("Day: " + data.ss[i][0]);
            document.write("<br/>");
            document.write("Time: " + data.ss[i][1]);
            document.write("<br/><br/>");
        }
    }
});

您实际上不应在应用程序中使用document.write。 这仅出于显示数据的目的。

假设您已经具有要解析的有效JSON StringjsonString )。 (如果您不知道如何从给定的URL中检索要使用XMLHttpRequest解析的String ,则必须首先检查该String 。)


使用纯JavaScript,您将必须添加Douglas Crockford的JSON库(或类似的东西),以便在没有本机实现的情况下提供解析Function

var json = json_parse(jsonString) ;

使用像jQuery这样的JavaScript库,这将是

var json = $.parseJSON(jsonString) ;

现在,遍历生成的JSON Object是另一个问题,因为在检索特定数据之前,您将必须了解其结构。 在这种特殊情况下-如果确实格式正确-您将必须执行以下操作:

var data = json.ss ;

     for(var i = 0 ; i < data.length ; i++) {

          var entry = data[i] ;

          var day = entry[0] ; //!! the Arrays seem to have a format where the first entry always contains the data and so forth...
          /* ... */

          // then do something with the data bits

     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM