railsでjsonをparseする
January 22, 2014
ruby
rails
rails4
json
parse
パース
jbuilder
basic
Gemfileに以下を追加
gem 'jbuilder', '~> 1.2'
Controllerにこんな感じで書く
json_data = JSON.parse(get_json)
second_level_items = json_data['children'].map {|c| c['child']}
second_level_items.each do |item|
genre = Genre.find_by_genre_id(item['genreId'])
genre = Genre.new(genre_id: item['genreId'], name: item['genreName']) unless genre
genre.save()
end
hoge = JSON.parse(hoge)
Viewにこんな感じで書く
<%= debug(hoge) %>
Basic認証付きならこんな感じ
begin
httpClient.set_auth("https://kyoto.smartercity.jp/api/v1/places", "username", "password");
data = httpClient.get_content("https://kyoto.smartercity.jp/api/v1/places", {
"rdf_type" => rdf_types.join(",")
});
@jsonData = JSON.parse data
rescue HTTPClient::BadResponseError => e
rescue HTTPClient::TimeoutError => e
end