使用 Javascript 解析格式错误的 JSON

发布于 2024-11-27 04:16:49 字数 469 浏览 1 评论 0原文

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

{"ss":[["星期四","7:00","决赛",,"BAL","19","ATL","20",,,"56808",,"PRE4 “,”201 5"],["星期四","7:00","决赛",,"否","10","GB","38",,,"56809",,"PRE4","2015" ]]}

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

我想在一个网站上设置这个来查看 NFL 球队的得分,这是一个有趣的项目,也是一个关于解析 JSON 的良好学习体验,因为我不太关心 Twitter 的东西。

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

I want to parse this content using Javascript. The data looks like this:

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

Every single tutorial online teaches you how to parse JSON using Twitter, but I am not quite sure how parsing with JSON works.

I would like to set this up on a website to view the NFL team scores for a fun project and a good learning experience about parsing JSON, as I could care less about Twitter stuff.

Is this possible? Any good tutorials to start with? Even some starting code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

波浪屿的海角声 2024-12-04 04:16:49

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

因此,您要么需要手动解析它,要么让 nfl.com 修复他们的 JSON。

作为替代方案,它们的 JSON 在使用 eval() 时确实解析成功,因此您可以使用以下内容解析它:

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

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

不过请注意,以这种方式解析 JSON 通常会受到反对(特别是当正在解析的数据正在被解析时)。由一个交付第三方源),因为如果数据中碰巧包含任何可执行代码,您就会遭受 XSS 攻击。

Generally speaking, you can use JSON.parse to do this. However, that snippet that you have does not appear to be strictly valid JSON (as seen here: http://jsfiddle.net/yK3Gf/ and also by validating the source JSON here: http://jsonlint.com/).

So you will either need to parse it by hand, or get nfl.com to fix up their JSON.

As an alternative, their JSON does parse successfully when using eval(), so you could parse it with something like:

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

...as shown here: http://jsfiddle.net/yK3Gf/1/

Though be aware that parsing JSON in this way is generally frowned upon (particularly when the data being parsed is being delivered by a third-party source), as it leaves you open to XSS attacks should the data happen to include any executable code inside of it.

我很OK 2024-12-04 04:16:49

我处于类似的位置 - 非 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 数据。以下示例行说明了该问题:

["周日","4:25","决赛",,"十","7","分钟","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;

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

I am in a similar position - non javascript expert working on a fun project to familiarize myself with javascript, ajax, and json.

I took three different steps to handle the problem. I welcome any feedback on improving the solution.

The first step is to query the nfl site to pull down the scores. Because the source of the json, the nfl site, is different from your site, you will have to work around the javascript security constraints against cross domain querying. I found this stackoverflow link to be a good reference. I used JSONP for the workaround. I used http://whateverorigin.org/ as the indirection site.

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

As others have pointed out, the nfl site returns invalid json data. The following sample line illustrates the problem:

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

Notice the empty array element values (the repeated commas with no data in between). So in my json callback function, I corrected the data by adding empty strings (two double quotes) to repeated commas before calling jquery to parse the json data:

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

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

Lastly, I created GameScores object to encapsulate the json data.

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;

I only added a few accessors as I did not need most of the data. Your needs may vary.

装迷糊 2024-12-04 04:16:49

我们使用 mootools 来完成类似的事情,但你也可以用纯 JavaScript 来完成:http://www.json.org/js.html

We are using mootools for stuff like that, but you can do it it plain JavaScript as well: http://www.json.org/js.html.

九命猫 2024-12-04 04:16:49

假设您已经有一个要解析的有效 JSON String (jsonString)。 (如果您不知道如何检索 String 以使用 XMLHttpRequest 从给定的 url 进行解析,您必须首先研究它。)


使用纯 JavaScript,您将拥有添加 Douglas Crockford 的 JSON 库(或类似的库),以便在没有本机实现的情况下提供解析函数:

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

     }

Let's assume you already have a valid JSON String (jsonString) to parse. (If you don't know how to retrieve a String to parse using XMLHttpRequest from the given url you will have to look into that first.)


With plain JavaScript you will have to add Douglas Crockford's JSON library (or something similar) in order to provide a parsing Function if there is no native implementation:

var json = json_parse(jsonString) ;

With a JavaScript library like jQuery this would be

var json = $.parseJSON(jsonString) ;

Now, traversing the resultant JSON Object is a whole other issue, because you will have to know its structure before you can retrieve specific data.
In this particular case -- if it was indeed well formed -- you would have to do the following:

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

     }
泅人 2024-12-04 04:16:49

您的主要问题是,根据 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 。这仅用于显示数据的示例目的。

Your main problem is that fact that the JSON your pulling in is malformed or not valid according to RFC 4627.

What you can do is grab the copy the JSON data and format it using this tool http://www.freeformatter.com/json-formatter.html

After you have the formatted version then you can use the jQuery ajax call

$.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/>");
        }
    }
});

You shouldn't actually use document.write in your application. This is only for example purpose of displaying the data.

灯角 2024-12-04 04:16:49

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

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

这会将 ,, 转换为 ,"",,并且在序列中有更多逗号的情况下也可以工作,因此 ,,, 变为 ,"","",。之后您可以使用 JSON.parse() 。

For this specific issue (the empty indexes within the arrays from the JSON response) I did a regex replacement with a lookahead assertion. Considering that request contains the XMLHttpRequest:

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

This will turn ,, into ,"", and will also work in case there are more commas in sequence, so ,,, becomes ,"","",. You can use JSON.parse() afterwards.

腻橙味 2024-12-04 04:16:49

这个格式错误的 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"
        ]
    ]
}

This malformed JSON can be parsed by the dirty-json NPM package (I am the author).

You can test a demo of the parser here: https://rmarcus.info/dirty-json

The parser interprets the JSON in your original question as equivalent to the following valid JSON:

{
    "ss": [
        [
            "Thu",
            "7:00",
            "Final",
            "BAL",
            "19",
            "ATL",
            "20",
            "56808",
            "PRE4",
            "2015"
        ],
        [
            "Thu",
            "7:00",
            "Final",
            "NO",
            "10",
            "GB",
            "38",
            "56809",
            "PRE4",
            "2015"
        ]
    ]
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文