Accessing JSON Objects in Ruby

Get a particular key value from json in ruby

parsed_json = ActiveSupport::JSON.decode(your_json_string)

will parse your string as


[{"KEY1"=>{"SUB_KEY1"=>"VALUE1", "SUB_KEY2"=>"VALUE2"}}, {"KEY2"=>{"SUB_KEY1"=>"VALUE1", "SUB_KEY2"=>"VALUE2"}}]

You should be able to access it using something like parsed_json[1]["KEY2"]["SUB_KEY1"]

ruby array of json object access a value

You can access you data using the following code:

data = JSON.parse(line) 
data.each do |d|
puts "#{d}"
puts "#{d} label: #{d["label"]}"
puts "#{d} value: #{d["value"]}"
end

After parsing the line with JSON.parse, your data variable will contain an array of hashes. When you iterate over this array , the block variable d is assigned to one of these hashes.

So, the first call to puts in this example will show the entire hash assigned to the variable d, and the second one will show the entire hash followed by the value assigned to the key label of that hash.

Similarly, the third line shows how to access the value stored in the value key.

How to access key, value in json / ruby

This is not valid JSON due to the trailing commas within your hashes. If you fix the commas, minify the JSON to make it easier to work with, and save it as a string, then you can begin to work with it in Ruby:

json = '{"testimonials":[{"office":"Test","authors":"Benjamin"},{"office":"consultant","authors":"Maxime "},{"office":"DAF","authors":"Alexandre"},{"office":"CEO","authors":"Raphaël"},{"office":"Consultant","authors":"Alexis"},{"office":"CEO,","authors":"Sylvain"}]}'

Now parse it into a real Ruby object:

hash = JSON.parse(json)
=> {
"testimonials" => [
[0] {
"office" => "Test",
"authors" => "Benjamin"
},
[1] {
"office" => "consultant",
"authors" => "Maxime "
},
[2] {
"office" => "DAF",
"authors" => "Alexandre"
},
[3] {
"office" => "CEO",
"authors" => "Raphaël"
},
[4] {
"office" => "Consultant",
"authors" => "Alexis"
},
[5] {
"office" => "CEO,",
"authors" => "Sylvain"
}
]
}

This is a hash that has an array of hashes inside it. You should access it using the standard methods for Hash and Array.

Start by getting the value of the only key in the hash, which is an array:

array = hash['testimonials']
=> [
[0] {
"office" => "Test",
"authors" => "Benjamin"
},
[1] {
"office" => "consultant",
"authors" => "Maxime "
},
[2] {
"office" => "DAF",
"authors" => "Alexandre"
},
[3] {
"office" => "CEO",
"authors" => "Raphaël"
},
[4] {
"office" => "Consultant",
"authors" => "Alexis"
},
[5] {
"office" => "CEO,",
"authors" => "Sylvain"
}
]

You indicated you wanted to fetch a value from index 4:

sub_hash = array[4]
=> {
"office" => "Consultant",
"authors" => "Alexis"
}

And that you wanted to return the string Alexis:

string = sub_hash['authors']
=> "Alexis"

Or put it all together in one line:

string = hash['testimonials'][4]['authors']
=> "Alexis"

Or one even shorter line:

JSON.parse(json)['testimonials'][4]['authors']
=> "Alexis"

Retrieving data from a JSON object in Ruby

you can convert to json with to_json

>   fruit_production.to_json
=> "{\"cuba\":{\"winter\":[{\"north\":1},{\"south\":null},{\"east\":4},{\"west\":4}],\"summer\":[{\"north\":null},{\"south\":5},{\"east\":\"\"},{\"west\":5}]},\"spain\":{\"fall\":[{\"north\":7},{}],\"summer\":[{\"north\":null},{\"south\":\"5\"},{\"east\":2},{\"west\":\"5\"}],\"spring\":[]}}"

As for retrieving the info from a json string, I think you're better off just to convert it back to a hash and work with that.

1, 3) You can get the yearly yield for each country by summing over season and region and taking the max.

note: your hash of yield by region is unnecessarily complex - you have an array of single-element hashes instead of a single hash indexed by region.

current: [{:north=>nil}, {:south=>"5"}, {:east=>2}, {:west=>"5"}]

better: {:north=>nil, :south=>"5", :east=>2, :west=>"5"}

However, this will work with what you've got, though I'm sure it can be simplified, (especially if you take my recommendation on the region-production structure - you can get rid of the sometimes-confusing inject function and just sum on the values of the hash):

by_country = Hash[fruit_production.map { |country, production| [country, production.map {|season, data| data.inject(0) { |sum, v| sum + v.values.map(&:to_i).sum } }.sum]}]

=> {:cuba=>19, :spain=>19}

Uh oh, you have a tie! I don't know what you want to do with that case, but you can just select one max pretty easily:

by_country.max_by { |k,v| v }
=> [:cuba, 19]

2) You can get a subset of fruit_production for European countries by selecting the elements of fruit_production whose key (after some string manipulation) matches one of the country names in the list:

 euro_fruit_production = fruit_production.select {|k,v| EURO_COUNTRIES.include?(k.to_s.titleize)}

=> {:spain=>{:fall=>[{:north=>7}, {}], :summer=>[{:north=>nil}, {:south=>"5"}, {:east=>2}, {:west=>"5"}], :spring=>[]}}

you can use that to work out seasonal totals. Good luck with the rest!

Ruby - Access value from json array

The result of your create_fields method with the specified parameters is the following:

[
{:field=>"Ford", :data=>{:type=>"Text", :description=>""}},
{:field=>"BMW", :data=>{:type=>"Text", :description=>""}},
{:field=>"Fiat", :data=>{:type=>"Text", :description=>""}}
]

It means that if you want to access the line belonging to "Ford", you need to search for it like:

2.3.1 :019 > arr.select{|e| e[:field] == "Ford" }
=> [{:field=>"Ford", :data=>{:type=>"Text", :description=>""}}]
2.3.1 :020 > arr.select{|e| e[:field] == "Ford" }[0][:data][:type]
=> "Text"

This is not optimal, because you need to search an array O(n) instead of using the pros of a hash. If there are e.g.: 2 "Ford" lines, you'll get an array which contains 2 elements, harder to handle collisions in field value.

It would be better if you created the array like:

def create_fields fields
fields_list = []

fields.each do |field|
# puts "adding_field to array: #{field}"
field_def = [field, { type: 'Text', description: '' } ]
fields_list.push field_def
end
Hash[fields_list]
end

If you choose this version, you can access the members like:

2.3.1 :072 > arr = create_fields ['Ford', 'BMW', 'Fiat']
=> {"Ford"=>{:type=>"Text", :description=>""}, "BMW"=>{:type=>"Text", :description=>""}, "Fiat"=>{:type=>"Text", :description=>""}}
2.3.1 :073 > arr["Ford"]
=> {:type=>"Text", :description=>""}
2.3.1 :074 > arr["Ford"][:type]
=> "Text"

Both of the above examples are Ruby dictionaries / Hashes.
If you want to create a JSON from this, you will need to convert it:

2.3.1 :077 > require 'json'
=> true
2.3.1 :078 > arr.to_json
=> "{\"Ford\":{\"type\":\"Text\",\"description\":\"\"},\"BMW\":{\"type\":\"Text\",\"description\":\"\"},\"Fiat\":{\"type\":\"Text\",\"description\":\"\"}}"

How to access JSON in Rails?

That's a regular params hash. Rails is usually smart enough to decode a JSON request and put the resulting object in params for you, and the hashrockets (=>) are a dead giveaway that it's a Ruby hash and not JSON. Formatted more nicely it looks like this:

{ "_json"  => [ { "id" => "1", "col" => 1, "row" => 1 },
{ "id" => "2", "col" => 2, "row" => 2 },
# ...
],
"ticket" => {}
}

You'll access it like any other Hash:

p params["_json"]
# => [ {"id"=>"1", "col"=>1, "row"=>1},
# {"id"=>"2", "col"=>2, "row"=>2},
# ...
# ]

p params["_json"][0]
# => {"id"=>"1", "col"=>1, "row"=>1}

p params["_json"][0]["id"]
# => "1"

p params["ticket"]
# => {}

It ought to be a HashWithIndifferentAccess, actually, so you should be able to use symbol keys as well:

p params[:_json][0][:id]
# => "1"

Dynamically accessing Ruby JSON object variables

Because your hash is getting created like this

{:"0.js"=>"js/0.js",
:"about-page.js"=>"js/about-page.js",
:"img/heart.png"=>"img/ae985f1437f67f39c4393e31c6785970.png",
:"index-page.js"=>"js/index-page.js",
:"init.js"=>"js/init.js",
:"main.js"=>"js/main.js"}

in order to access it you need to do @file[:"0.js"]



Related Topics



Leave a reply



Submit