How to deserialize JSON objects

deserialization, json, ruby-on-rails

Solution

Use Ruby's JSON library.

res = '{"total":"1200.0","used":"35.0","available":1165.0}'
JSON.parse(res) # => {"total"=>"1200.0", "used"=>"35.0", "available"=>1165.0}

Note: If you're on Ruby 1.8.X you may have to require the json class. Rails requires it for you if you are working within a rails app.

Problem

I'm trying to use the get request by: ``` req = Net::HTTP::Get.new("/api/v1/users/external/1/features/DOWNLOAD7ab8d82b40/alloc?paymentPlanId=PRO_SUBSCRD725FCCCC6"); req.add_field('ISV_API_KEY', '548f3d4b34ffdb2f294a870a9728af6940a75b66ba944d8ab6eef5a7543ca3db'); req.add_field('ISV_API_SECRET', '69dafa8923f2b0da8153e6bcca3841de0fa88f1a031a5eb1946e54eb982cef48'); res = Net::HTTP.start("localhost", 3000) {|http| res = http.request(req) } ``` 'postman` is an application that shows me the result of this request According to the `postman`, this request returns me: ``` { "total":"1200.0", "used":"35.0", "available":1165.0 } ``` How can I deserialize this Json object? Assuming I want the "used" parameter. I tried: ``` json_string = req2.to_json puts json_string ``` but I got: ``` {"accept":["*/*"],"user-agent":["Ruby"],"isv_api_key":["548f3d4b34ffdb2f294a870a9728af6940a75b66ba944d8ab6eef5a7543ca3db"],"isv_api_secret":["69dafa8923f2b0da8153e6bcca3841de0fa88f1a031a5eb1946e54eb982cef48"]} ``` I also tried: ``` puts JSON.parse(res) ``` but I got: ``` can't convert Net::HTTPOK into String ```

Original source