How to convert a ruby hash object to JSON?
One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).
So, take a look here:
car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
# from (irb):11
# from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"
As you can see, requiring json
has magically brought method to_json
to our Hash
. How to convert ruby formatted json string to json hash in ruby?
You can try eval method on temp json string
Example:
eval(temp)
This will return following hash{"accept"=>"*/*", "host"=>"localhost:4567", "version"=>"HTTP/1.1", "user_agent"=>"curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3", "http_token"=>"375fe428b1d32787864264b830c54b97"}
Hope this will help.Thanks
Convert JSON string to hash
It's most likely because this isn't valid JSON. Change your single quotes to double quotes, like so:
test = '[{"domain": "abc.com"}, {"domain": "def.com"}, {"domain": "ghi.com"}]'
An explanation can be found here, and you can validate your JSON here. How to convert JSON to a Ruby hash
What about the following snippet?
require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}
Parsing a JSON string in Ruby
This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string
, like so:
require 'json'
JSON.parse(json_string)
If you’re using an older Ruby, you may need to install the json gem.There are also other implementations of JSON for Ruby that may fit some use-cases better:
- YAJL C Bindings for Ruby
- JSON::Stream
How can I convert a string in my JSON file into a Ruby hash?
I think something like this would help:
def media_url
tweet = self.object
JSON.parse(tweet.media[0].gsub('=>', ':'))["media_url"]
end
You need to replace =>
with :
in order for JSON.parse
to workOr
To get the complete hash you can use a more generic method like media
:
def media
tweet = self.object
JSON.parse(tweet.media[0].gsub('=>', ':'))
end
How to convert a hash to JSON without the converted string being full of backslashes
It seems like you are confused about the actual content of the string. The backslashes are part of the string representation, and are not actually in the string.
Take for example '"'
a single character "
. When you enter this into irb the output will be:
s = '"'
#=> "\""
From the result "\""
the starting "
and ending "
mark the begin and ending of the string while \"
is an escaped double quote, and represents a single "
. The reason this double quote is escaped is because you want Ruby to interpret it as an "
character, not as the end of the string.You can view the actual contents of the string without escape characters by printing it to the console.
puts s
# "
#=> nil
Here you can see that there is no backslash in the contents of the string.The same applies for your
to_json
call, which returns a string:data = {"a" => "b", "c" => "d", "e" => "f"}
json = data.to_json
#=> "{\"a\":\"b\",\"c\":\"d\",\"e\":\"f\"}"
puts json
# {"a":"b","c":"d","e":"f"}
#=> nil
Like you can see there are no backslashes in the contents of the string, only in the string representation. How to turn into a hash what has been made into a string of a hash?
str = "{ H: 50, Q: 25, D: 10, N: 5, P: 1 }"
str.gsub(/(\S+): +(\d+)/).with_object({}) { |_,h| h[$1.to_sym] = $2.to_i }
#=> {:H=>50, :Q=>25, :D=>10, :N=>5, :P=>1}
This employs the form of String#gsub that takes an argument and no block, returning an enumerator that can be chained to Enumerator#with_object. This form of gsub
merely generates matches; it makes no substitutions.One advantage of this construct is that it avoids the creation of temporary arrays.
The regular expression can be written in free-spacing mode to make it self-documenting.
/
(\S+) # match 1+ characters other than whitespaces, save to capture group 1
:[ ]+ # match ':' followed by 1+ spaces
(\d+) # match 1+ digits, save to capture group 2
/x # free-spacing regex definition mode
Related Topics
How to Access Parent/Sibling Module Methods
How to Override a Variable in a Ruby Subclass Without Affecting The Superclass
How to Access Sinatra App on Host Machine with Vagrant Forwarded Ports
Script Executes Successfully in Commandline But Not as a Cronjob
"Previous Post" and "Next Post" Link in Show View (Nested Resources)
How to Send a Keep-Alive Packet Through Websocket in Ruby on Rails
Ruby/Active Record: Custom Sorting Order
Facebook Redirect Url in Ruby on Rails Open Ssl Error
How to Create Thor::Group Generators as Args of My_Command
Should I Delete Migration After Rollback
How to Make Fish Shell Use an Rvm Ruby by Default
Is It a Bad Practice to Randomly-Generate Test Data
How to Make Devise Registrationscontroller to Show Sign_Up Page Only If User Is Already Signed In
Running Capybara Without Rack Produces Errors When Using Url Parameters
How to Install Wraith on Windows 7
Rails Application Helper Didn't Support Chinese Characters
Rails 3.1 Has_One Nested Resource: Routing Not Generating "All" Paths