简体   繁体   中英

Hashie::Rash being converted to string instead on Json or hash in Ruby on Rails

I am using an API whose reply is in form of Hashie::Rash. an example:

country = #<Hashie::Rash confidence="99" geoname_id=3175395 iso_code="IT" names=#<Hashie::Rash de="Italien" en="Italy" es="Italia" fr="Italie" ja="イタリア共和国" pt_br="Itália" ru="Италия" zh_cn="意大利">>

country.class = Hashie::Rash

I want to convert this to Json, to look like

{"iso_code":"IT","names": {"pt_br":"Itália","es":"Italia","ru":"Италия","en":"Italy","zh_cn":"意大 利","fr":"Italie","de":"Italien","ja":"イタリア共和 国"},"confidence":"99","geoname_id":3175395}

when I try using to_json(), it produces this:

"{\"iso_code\":\"IT\",\"names\":{\"pt_br\":\"Itália\",\"es\":\"Italia\",\"ru\":\"Италия\",\"en\":\"Italy\",\"zh_cn\":\"意大利\",\"fr\":\"Italie\",\"de\":\"Italien\",\"ja\":\"イタリア共和国\"},\"confidence\":\"99\",\"geoname_id\":3175395}"

whose class is a string.

How can I convert it to a JSON or Hash form??. Thanks

I assume that you have to_json format data look like:

str =  "{\"iso_code\":\"IT\",\"names\":{\"pt_br\":\"Itália\",\"es\":\"Italia\",\"ru\":\"Италия\",\"en\":\"Italy\",\"zh_cn\":\"意大利\",\"fr\":\"Italie\",\"de\":\"Italien\",\"ja\":\"イタリア共和国\"},\"confidence\":\"99\",\"geoname_id\":3175395}"

then go to terminal and require json and parse it like bellow:

require 'json'
ob = JSON.parse(str)

Then you get json formatted output there and this will be look like:

{"iso_code"=>"IT", "names"=>{"pt_br"=>"Itália", "es"=>"Italia", "ru"=>"Италия", "en"=>"Italy", "zh_cn"=>"意大利", "fr"=>"Italie", "de"=>"Italien", "ja"=>"イタリア共和国"}, "confidence"=>"99", "geoname_id"=>3175395}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM