Ruby JSON解析器不喜欢空白是合理的吗?
我使用的是json_pure-1.4.6,它在解析来自Chrome的SpeedTracer的数据时遇到了问题。特别是它的失败是这样的:Ruby JSON解析器不喜欢空白是合理的吗?,ruby,json,Ruby,Json,我使用的是json_pure-1.4.6,它在解析来自Chrome的SpeedTracer的数据时遇到了问题。特别是它的失败是这样的: 705: unexpected token at '{"type":2147483642,"time":8872.551025390625,"data":{"identifier":1,"time":1295485209.698246,"request":{"url":"http://localhost:3000/login/new","httpMethod":
705: unexpected token at '{"type":2147483642,"time":8872.551025390625,"data":{"identifier":1,"time":1295485209.698246,"request":{"url":"http://localhost:3000/login/new","httpMethod":"GET","httpHeaderFields":{"User-Agent":"Mozilla/5.0'
{"type":2147483642,"time":8872.551025390625,"data":{"identifier":1,"time":1295485209.698246,"request":{"url":"http://localhost:3000/login/new","httpMethod":"GET","httpHeaderFields":{"User-Agent":"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.634.0 Safari/534.16","Accept":"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"}},"redirectResponse":{"isNull":true}},"sequence":116}
这显然是一个不完整的陈述,但在文件本身中,它看起来是这样的:
705: unexpected token at '{"type":2147483642,"time":8872.551025390625,"data":{"identifier":1,"time":1295485209.698246,"request":{"url":"http://localhost:3000/login/new","httpMethod":"GET","httpHeaderFields":{"User-Agent":"Mozilla/5.0'
{"type":2147483642,"time":8872.551025390625,"data":{"identifier":1,"time":1295485209.698246,"request":{"url":"http://localhost:3000/login/new","httpMethod":"GET","httpHeaderFields":{"User-Agent":"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.634.0 Safari/534.16","Accept":"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"}},"redirectResponse":{"isNull":true}},"sequence":116}
我尝试通过JSONLint运行它,但它没有抱怨:
{
"type": 2147483642,
"time": 8872.551025390625,
"data": {
"identifier": 1,
"time": 1295485209.698246,
"request": {
"url": "http://localhost:3000/login/new",
"httpMethod": "GET",
"httpHeaderFields": {
"User-Agent": "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.634.0 Safari/534.16",
"Accept": "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
}
},
"redirectResponse": {
"isNull": true
}
},
"sequence": 116
}
由于它在空白处失败,我尝试删除“User Agent”行中的所有空白,然后json_pure无误地解析了它。这是一个纯json错误吗?我刚刚将json字符串粘贴到一个文件中,然后运行:
require 'rubygems'
require 'json/pure'
str = File.open('pasted.json').read
x = JSON.parse(str)
…并获得了预期值,没有错误
ruby -v
=> ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-darwin9.8.0]
gem list json_pure
=> json_pure (1.4.6)
很明显,你的设置有点古怪,但我不知道是什么。嗯。这是个好消息,谢谢。我将通过发布更新来了解交易内容。我找到了答案,在主要部分添加了评论。多亏了Bill,我更仔细地了解了解析器试图解析的内容。原来我的问题只是我犯了个愚蠢的错误。我从HTML中剔除所有JSON数据,并试图将其作为每行一条语句来处理。不幸的是,我在做一个不合格的“拆分”,所以它在每个空白处拆分,而不是在每个换行符上拆分。我最初测试的SpeedTrace数据没有通用空格,这导致了我的困惑。切换到“拆分”\n“解决了我的问题。