Luca G. Soave
Luca G. Soave

Reputation: 12689

Yajl::ParseError: lexical error: invalid char in json text

Parsing with YAJL Ruby I get the following error

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

How can I get rid of that ?

UPDATE (tanks to Howard):

it was just a metter of adding to_json method to 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, ...

then it works :

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 > 

just because resp.body, was not 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", ...

Upvotes: 2

Views: 10302

Answers (1)

Howard
Howard

Reputation: 39207

Your text isn't an allowed JSON object. The token => should no be present but a colon : instead.

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

Upvotes: 3

Related Questions