gFontaniva
gFontaniva

Reputation: 903

Ruby hash to json with JSON.parse error

I'm trying to do a json to hash, but I give this

JSON.parse({"tag":"DownloadRequest","hash":"c8\u0006ùM]ÁaSßwÃ9\u0007Ãò\u0013Â4lÊ·|j\\ëç","part_number":0})
TypeError: exception class/object expected

How I fix it?

Upvotes: 0

Views: 126

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84443

What you're currently passing to JSON#parse isn't a valid Ruby Hash object; it's just raw JSON. JSON#parse expects a string containing valid JSON instead. Everything works fine if you wrap your JSON inside a string like so:

require 'json'
str = '{"tag":"DownloadRequest","hash":"c8\u0006ùM]ÁaSßwÃ9\u0007Ãò\u0013Â4lÊ·|j\\ëç","part_number":0}'
JSON.parse str

It now returns:

{"tag"=>"DownloadRequest", "hash"=>"c8\u0006ùM]ÁaSßwÃ9\aÃò\u0013Â4lÊ·|jëç", "part_number"=>0}

Upvotes: 2

Related Questions