Yajl :: ParseError:词法错误:json文本中的char无效

时间:2013-03-31 09:16:16

标签: ruby regex json parsing yajl

使用YAJL Ruby进行解析我收到以下错误

2.0.0-p0 :048 >   Yajl::Parser.parse "#{resp.body}"
Yajl::ParseError: lexical error: invalid char in json text.
                                  {"id"=>2126244, "name"=>"bootstrap",
                     (right here) ------^

我该怎样摆脱它?

更新(坦克到霍华德):

它只是向resp.body添加to_json方法的一个方法:

2.0.0-p0 :183 > parsed = Yajl::Parser.parse resp.body.to_json
 => {"id"=>2126244, "name"=>"bootstrap", "full_name"=>"twitter/bootstrap", "owner"=>{"login"=>"twitter", "id"=>50278, ...

然后它起作用:

2.0.0-p0 :184 > parsed.class
 => Hash 
2.0.0-p0 :185 > parsed["id"]
 => 2126244 
2.0.0-p0 :186 > parsed["name"]
 => "bootstrap" 
2.0.0-p0 :187 > parsed["full_name"]
 => "twitter/bootstrap" 
2.0.0-p0 :188 > parsed["owner"]
 => {"login"=>"twitter", "id"=>50278, "avatar_url"=>"https://secure.gravatar.com/avatar/2f4a8254d032a8ec5e4c48d461e54fcc?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-org-420.png", "gravatar_id"=>"2f4a8254d032a8ec5e4c48d461e54fcc", "url"=>"https://api.github.com/users/twitter", "html_url"=>"https://github.com/twitter", "followers_url"=>"https://api.github.com/users/twitter/followers", "following_url"=>"https://api.github.com/users/twitter/following", "gists_url"=>"https://api.github.com/users/twitter/gists{/gist_id}", "starred_url"=>"https://api.github.com/users/twitter/starred{/owner}{/repo}", "subscriptions_url"=>"https://api.github.com/users/twitter/subscriptions", "organizations_url"=>"https://api.github.com/users/twitter/orgs", "repos_url"=>"https://api.github.com/users/twitter/repos", "events_url"=>"https://api.github.com/users/twitter/events{/privacy}", "received_events_url"=>"https://api.github.com/users/twitter/received_events", "type"=>"Organization"} 
2.0.0-p0 :189 > 

仅仅因为resp.body,不是json:

2.0.0-p0 :197 > print resp.body
{"id"=>2126244, "name"=>"bootstrap", ... 

2.0.0-p0 :196 > print resp.body.to_json
{"id":2126244,"name":"bootstrap", ...

1 个答案:

答案 0 :(得分:3)

您的文本不是允许的JSON对象。令牌=>不应该出现,而是冒号:

{
    "id" : 2126244,
    "name" : "bootstrap",
    ...
}