How to Convert Json to a Ruby Hash

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"}

How to convert JSON response to hash, and extract specific key and value

You can use select to extract the expected key and value.
Please refer ruby select.

def specific_currency(currency)
@response_body ||= RestClient.get(@weather).body
@hash_response = JSON.parse(@response_body)['rates'].select { |element| element.to_s == currency }
end

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 work

Or

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

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 hash, search for and change a value

I understand your JSON may look like this:

"{\"features\":{\"additional-options\":true},\"values\":{\"lo-value\":34,\"hi-value\":554},\"persons\":[{\"name\":\"john\",\"member\":true,\"current\":false,\"sponsor\":\"pete\",\"profile\":\"\",\"credits\":[\"04\"],\"linked\":[\"philip\",\"guy\"],\"maptools\":[\"crossfit\",\"soccer\",\"running\"]},{\"name\":\"mary\",\"member\":true,\"current\":false,\"sponsor\":\"judy\",\"profile\":\"\",\"credits\":[\"all\"],\"activities\":[\"swimming\",\"cycling\",\"running\"]}],\"data_map\":[1122,3234]}"

I suggest using an OpenStruct to organize your data:

your_struct_name =  JSON.parse(yourJson, object_class: OpenStruct)

Then you get all the things you want. For the operations you show:

#change_key(hash, "features.additional-options", false)
your_struct_name.features['additional-options'] = false
#this one above you set in this hash-like manner because of the '-' in the middle of the key. Otherwise you could just do your_struct_name.features.additional_options = false

#del_from_array(hash, "persons.name=mary.activities", "cycling")
your_struct_name.persons.last.activities.delete('swimming')

# or selecting by name:
your_struct_name.persons.select {|person| person.name == 'mary' }.first.activities.delete('swimming')

#add_to_array(hash, "persons.name=mary.activities", "hockey")
your_struct_name.persons.last.activities << 'hockey'

#del_key(hash, "data_map")
your_struct_name.delete_field('data_map')

#del_key(hash, persons.name=john.profile)
...

#del_key(hash, persons.name=mary.credits)
...

Then, after you make your changes, you can use:

your_struct_name.to_h.to_json

You can also use the method as_json to get a structure very similar to what you showed on the question:

your_struct_name.as_json

OpenStruct is very nice to deal with data that has a changing structure. If you have data that can be "modeled", has a name you can call, has some attributes you can predict, and even methods you will use for this data, I suggest you to create a Class to describe this data, its properties and attributes (it can even inherit from OpenStruct). Then work inside this Class domain, creating a layer of abstraction. This way your code gets a lot more robust and readable. Don't forget to create automatic tests! It saves you a lot of time.

The way you organize and abstract your data, and specially the way you name entities are things that have high impact on code quality.

For further reading see: Object and ActiveData.

Convert JSON into a Hash

Solved my issues using:

object = self.as_json.with_indifferent_access
# => allowing me to use a symbol key instead of a string

ok_vals = object[:values][:ok].as_json.gsub(/\=\>/, ':')
# => allowing to change json string '{"val1"=>"val1", "val2"=>"val2"}' to '{"val1":"val1", "val2":"val2"}'
ok_vals = JSON.parse(ok_vals)
# => which transform json string to hash {val1: "val1", val2: "val2"}

Feel free to make any suggestions to this code. Thanks for the help.

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

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.

convert JSON array to Ruby Hash (of hashes)

My question did not show the full string I was trying to JSON.parse. I only put what I was trying to parse. I accidentally left some floating data before the JSON part of my string. Now that I have deleted that, it is working.



Related Topics



Leave a reply



Submit