Question

How can i access the year from the json shown below which i fetch from a url and decode using

obj = ActiveSupport::JSON.decode(response.body)

The folloowing is the response i get after decode

{
  "educations"=>{"_total"=>1, 
                 "values"=>[
                            {"id"=>18234534505, 
                             "schoolName"=>"Test", 
                             "startDate"=>{"year"=>2013}
                            }
                           ]
                }
}

How can i access the year? I can able to access the values as

obj['educations']['values']

and it responds as

{"id"=>18234534505, "schoolName"=>"Test", "startDate"=>{"year"=>2013}}

but how can i get the year? please help me.

UPDATE:

how can i add if condition here?

obj["educations"]["values"].each do |value|

@user_education = Education.new("start_date" => value['startDate']['year'], "education_id" => value['id'], "school_name" => value['schoolName'])

end

so here if there is no year then how can i check as you said? and there may also be endDate similar to the startDate so how can i check this?

Was it helpful?

Solution

Just access the key as

obj["educations"]["values"].first["startDate"]["year"]

# above is answer if there is always one array inside `obj["educations"]["values"]`

For multiple arrays's

year = []

obj["educations"]["values"].each do |object|
  year << object["startDate"]["year"] if !object["startDate"].blank? and !object["startDate"]["year"].blank?
end

update :

If you want to add attributes to the

@user_education = Education.new
@user_education.start_date = value['startDate']['year'] if !value['startDate'].blank? and !value['startDate']['year'].blank?
@user_education.education_id = value['id'] if !value['id'].blank?
@user_education.school_name = value['schoolName'] if !value['schoolName'].blank?

Similarly for any other attribute..

obj["educations"]["values"].each do |value|
  @user_education = Education.new("education_id" => value['id'], "school_name" => value['schoolName'])
  @user_education.start_date = value["startDate"]["year"] if !value["startDate"].blank? and !object["startDate"]["year"].blank?
  @user_education.save! #To save the object
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top