I'm working getting tweets from the Twitter API in my Rails backend. I'm able to create tweets in my db and then render the tweets as a JSON. But part of the tweet is still showing up as a string. How can I convert this specific part into a Ruby hash so that I can access the key:value pairs?
I've tried .serializable_hash, .hash, to_json, but either the data type is wrong (needs to be an array) or it just adds more \ characters
.strip, .split, .gsub also didn't work
when I puts the string, it looks like a hash, but I'm not able to save that output
This is how the json is being rendered:
"media": [
"{\"id\"=>1159941035461529600, \"id_str\"=>\"1159941035461529600\", \"indices\"=>[62, 85], \"media_url\"=>\"http://pbs.twimg.com/media/EBjwOeMVUAAVOia.jpg\", \"media_url_https\"=>\"https://pbs.twimg.com/media/EBjwOeMVUAAVOia.jpg\", \"url\"=>\"https://t.asdco/mFwUSlGEpv\", \"display_url\"=>\"pic.twitter.com/mFwUSlGEpv\", \"expanded_url\"=>\"https://twitter.com/CommonBlackGirI/status/1159941046161170432/photo/1\", \"type\"=>\"photo\", \"sizes\"=>{\"thumb\"=>{\"w\"=>150, \"h\"=>150, \"resize\"=>\"crop\"}, \"medium\"=>{\"w\"=>1122, \"h\"=>819, \"resize\"=>\"fit\"}, \"large\"=>{\"w\"=>1122, \"h\"=>819, \"resize\"=>\"fit\"}, \"small\"=>{\"w\"=>680, \"h\"=>496, \"resize\"=>\"fit\"}}}"
]
I tried to create a method in the serializer file, but that didn't work because it's just string, not a traversable hash
def media_url
tweet = self.object
tweet.media[0]
end
I'd like to convert the string above into a Ruby hash so that I can get the media_url for each tweet
JSON.parseseems to be what you're looking forto_jsonon it when rendering.media_urldoesn't render, but something else does.h[:"media"][0]is not valid json ( it looks like aHashconverted to aStringviato_s) If you need to convert aHashto JSON the method isto_jsonbut you should explain how this is being generated in the first place or just use thetwittergem and not worry as much about the implementation