2

使用 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) ------^

我怎样才能摆脱它?

更新(坦克霍华德):

只需将 to_json 方法添加到 resp.body :

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", ...
4

1 回答 1

3

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

{
    "id" : 2126244,
    "name" : "bootstrap",
    ...
}
于 2013-03-31T09:22:00.907 回答