告诉错误位置的JavaScript JSON解析器 [英] JavaScript JSON parser that tells error position

查看:119
本文介绍了告诉错误位置的JavaScript JSON解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在解析使用WebSocket收到的JSON时遇到了一些麻烦(原始问题 - 解析使用WebSocket收到的JSON导致错误)。 JSON字符串本身是有效的(使用多个JSON验证器进行测试),但JSON.parse会引发异常。我试图找出它无法解析的确切内容,但我唯一得到的是SyntaxError:unexpected_token ILLEGAL,它没有说明失败令牌的确切位置在哪里。有没有办法提取这些信息?

I've been having some troubles with parsing JSON that is received with WebSocket (original question - Parse JSON received with WebSocket results in error). The JSON string itself is valid (tested with several JSON validators), but JSON.parse throws an exception. I am trying to figure out what is it exactly that it cannot parse, but the only thing I'm getting is "SyntaxError: unexpected_token ILLEGAL", it doesn't say where is the exact position of the failed token. Is there any way of extracting such information?

更新:如果我将该JSON字符串复制粘贴到静态文件(例如数据)。 json)然后检索它并使用相同的函数(JSON.parse)解析它 - 然后它工作正常。
所以我假设有一些棘手的事情,我想到换行符号(可能有\ n而不是\\\\ n或反之亦然)但完全删除所有的换行符没有救命。我认为它很可能是一个编码问题,但数据是通过websocket接收的,根据文档它是utf-8字符串。

Update: If I copy-paste that JSON string to a static file (e.g. "data.json") and then retrieve it and parse it with the same function (JSON.parse) - then it works fine. So I'm assuming there's something tricky going on, I thought of newline symbol (may be there was \n instead of \r\n or vice versa) but completely removing all the line breaks didn't help. I would think that it very well may be an encoding problem, but the data is received via websocket and according to documentation it's utf-8 string.

第二次更新:如果我从这里使用json_parse,它的工作正常: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
然后它工作正常!这是否意味着这是Chrome使用的JSON.parse实现中的错误或什么?

2nd Update: IT WORKS just fine if I use "json_parse" from here: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js Then it works fine! Does that mean this is a bug in "JSON.parse" implementation used by Chrome or what?

谢谢。

推荐答案

您可以从某个地方复制JSON.parse()的实现(比如jQuery),更改它的名称以便您可以直接调用它,调整实现以便它永远不会检测内置解析器,因此它始终使用JS解析器,然后更改代码以使用解析器的新JS版本,然后在javascript调试器中跟踪它,直到找到它不喜欢的内容。

You could copy an implementation of JSON.parse() from somewhere (like out of jQuery), change it's name so you can call it directly, tweak the implementation so that it never detects the built-in parser so it always uses the JS parser and then change your code to use the new JS version of the parser, then trace through it in a javascript debugger until you find what it doesn't like.

这篇关于告诉错误位置的JavaScript JSON解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆