How can I save external JSON data to DB(sqlite) with Rails - ruby-on-rails

I have a form to add json url form, If user add json url and submit form, I want to save all json data to db.[form]1
Fetching json data from url using httparty gem works perfectly, now to store json data to db json_url
json data
{
"restaurant_name": "Restaurant 3",
"address": "xyz address",
"country": "United States",
"currency": "USD",
"client_key": "12345",
"client_name": "Client 3",
"client_email": "test3#mail.com",
"client_phone": "9876",
"product_tier": "tier1",
"brand_logo_large": {
"ID": 37,
"id": 37,
"title": "bait-al-bahar-logo-design",
"filename": "bait-al-bahar-logo-design.png",
"filesize": 105071,
"url": "http://codekyt.in/froodle-wp/wp-content/uploads/2019/01/bait-al-bahar-logo-design.png",
"link": "http://codekyt.in/froodle-wp/projects/res-1-client-1/bait-al-bahar-logo-design/",
"alt": "",
"author": "1",
"description": "",
"caption": "",
"name": "bait-al-bahar-logo-design",
"status": "inherit",
"uploaded_to": 35,
"date": "2019-01-04 11:11:48",
"modified": "2019-01-04 11:13:01",
"menu_order": 0,
"mime_type": "image/png",
"type": "image",
"subtype": "png",
"icon": "http://codekyt.in/froodle-wp/wp-includes/images/media/default.png",
"width": 600,
"height": 500,
"sizes": {
"thumbnail": "http://codekyt.in/froodle-wp/wp-content/uploads/2019/01/bait-al-bahar-logo-design-150x150.png",
"thumbnail-width": 150,
"thumbnail-height": 150,
"medium": "http://codekyt.in/froodle-wp/wp-content/uploads/2019/01/bait-al-bahar-logo-design-300x250.png",
"medium-width": 300,
"medium-height": 250,
"medium_large": "http://codekyt.in/froodle-wp/wp-content/uploads/2019/01/bait-al-bahar-logo-design.png",
"medium_large-width": 600,
"medium_large-height": 500,
"large": "http://codekyt.in/froodle-wp/wp-content/uploads/2019/01/bait-al-bahar-logo-design.png",
"large-width": 600,
"large-height": 500
}
}
}
I created a form to user & added json url,
<%= form_tag("/settings/json_url", method: "post") do %>
<%= label_tag :json_url %>
<%= text_field_tag :json_url %>
<%= submit_tag 'submit' %>
<% end %>
In db,
t.string :key
t.string :value
t.string :json_url
In controller,
def json_url
# I am getting confused here
end

Related

Parse JSON from HTTParty using Ruby on Rails

I am implementation of data from a JSON file to a Ruby on Rails application by using HTTparty gem, but I am getting Error no implicit conversion of String into Integer
I refered this tutorial link
My json data,
{
"restaurant_name": "Restaurant 3",
"address": "xyz address",
"country": "United States",
"currency": "USD",
"client_key": "12345",
"client_name": "Client 3",
"client_email": "test3#mail.com",
"client_phone": "9876",
"product_tier": "tier1",
"brand_logo_large": {
"ID": 37,
"id": 37,
"title": "bait-al-bahar-logo-design",
"filename": "bait-al-bahar-logo-design.png",
"filesize": 105071,
"url": "http://codekyt.in/froodle-wp/wp-content/uploads/2019/01/bait-al-bahar-logo-design.png",
"link": "http://codekyt.in/froodle-wp/projects/res-1-client-1/bait-al-bahar-logo-design/",
"alt": "",
"author": "1",
"description": "",
"caption": "",
"name": "bait-al-bahar-logo-design",
"status": "inherit",
"uploaded_to": 35,
"date": "2019-01-04 11:11:48",
"modified": "2019-01-04 11:13:01",
"menu_order": 0,
"mime_type": "image/png",
"type": "image",
"subtype": "png",
"icon": "http://codekyt.in/froodle-wp/wp-includes/images/media/default.png",
"width": 600,
"height": 500,
"sizes": {
"thumbnail": "http://codekyt.in/froodle-wp/wp-content/uploads/2019/01/bait-al-bahar-logo-design-150x150.png",
"thumbnail-width": 150,
"thumbnail-height": 150,
"medium": "http://codekyt.in/froodle-wp/wp-content/uploads/2019/01/bait-al-bahar-logo-design-300x250.png",
"medium-width": 300,
"medium-height": 250,
"medium_large": "http://codekyt.in/froodle-wp/wp-content/uploads/2019/01/bait-al-bahar-logo-design.png",
"medium_large-width": 600,
"medium_large-height": 500,
"large": "http://codekyt.in/froodle-wp/wp-content/uploads/2019/01/bait-al-bahar-logo-design.png",
"large-width": 600,
"large-height": 500
}
}
In model,
include HTTParty
In controller
def index
require 'httparty'
#category = HTTParty.get(
'http://codekyt.in/froodle-wp/wp-json/data/v2/projects?client_key=12345',
:headers =>{'Content-Type' => 'application/json'}
)
end
In gemfile,
gem 'httparty'
gem 'json'
In view,
<%#category.each do |category|%>
<%=category["restaurant_name"]%>
<%=category["country"]%>
<%=category["currency"]%>
<%=category["usd"]%>
<%=category["client_key"]%>
<%=category["client_name"]%>
<%=category["client_email"]%>
<%=category["client_phone"]%>
<%=category["product_tier"]%>
<%=category["brand_logo_large"]%>
<%end%>
HTTParty.get returns an encapsulated response type of class HTTParty::Response, you need to retrieve the parsed response from that by:
response = HTTParty.get(
'http://codekyt.in/froodle-wp/wp-json/data/v2/projects?client_key=12345',
:headers =>{'Content-Type' => 'application/json'}
)
#category = response.parsed_response # this will return the json.
Also you do not need to iterate on #category in your case, the json object is singular and you can directly use it:
<%=#category["restaurant_name"]%>
<%=#category["country"]%>
<%=#category["currency"]%>
<%=#category["usd"]%>
<%=#category["client_key"]%>
<%=#category["client_name"]%>
<%=#category["client_email"]%>
<%=#category["client_phone"]%>
<%=#category["product_tier"]%>
<%=#category["brand_logo_large"]%>

Defining Array of Objects in Swagger Documentation

I'm using swagger for quite a bit now, we have started documenting our code using it, in one place there's an API response which returns multiple objects in the included block.
Example:
{
"data": {
"id": "1",
"type": "schoolPositions",
"attributes": {
"description": "teases the students",
"mustHaves": "principle"
},
"relationships": {
"schoolLocation": {
"data": {
"id": "72",
"type": "schoolLocations"
}
},
"schoolCompensation": {
"data": {
"id": "75",
"type": "schoolCompensations"
}
},
"jobSpecs": {
"data": [
{
"id": "82",
"type": "schoolAttachments"
}
]
}
}
},
"included": [
{
"id": "72",
"type": "schoolLocations",
"attributes": {
"city": "Berhampore",
"state": "West Bengal",
"postalCode": "742101",
"country": "India",
"globalRegionId": 30,
"regionId": 683
}
},
{
"id": "75",
"type": "schoolCompensations",
"attributes": {
"salary": "",
"bonus": "",
"equity": "",
"currencyId": null,
"equityType": "percent",
"salaryDescription": null
}
},
{
"id": "82",
"type": "schoolAttachments",
"attributes": {
"attachmentType": "JobSpecificationAttachmentType",
"fileFileName": "vs.jpg",
"fileContentType": "image/jpeg",
"fileFileSize": 2410039,
"fileUpdatedAt": "2018-12-12T07:06:38Z",
"downloadUrl": "001-vs.jpg?1544598398",
"klass": "SchoolAttachments"
}
}
]
I have wasted an entire day on the internet and documentation trying to document the included part, but I'm going wrong somewhere
response 200 do
key :description, 'School Data'
schema do
property :data do
key :type, :array
items do
key :'$ref', :School
end
end
property :included do
key :type, :array
items do
key :'$ref', :SchoolLocations
key :'$ref', :SchoolCompensations
key :'$ref', :SchoolAttachments
end
end
end
end
This shows only the SchoolAttachments in the included part.
I have tried using allOff but it doesn't work.

Build a grouped JSON object

I am building a Rails/Backbone app and I will show users in a table.
I want to create a JSON tree which is grouped on the user ID/Name.
This is how it looks now
[{
"total_entries": 2
},
{
"entries": [{
"id": 21,
"status": "pending",
"starts_at_date": "2018-02-02",
"starts_at_time": "12:00",
"ends_at_date": "2018-02-02",
"ends_at_time": "12:00",
"description": "",
"ttype": "vacation",
"sum": 0,
"user": {
"id": 1,
"fullname": "Marcus Lurem"
},
"timetype": null,
"pause": 0,
"can_manage": true
},
{
"id": 22,
"status": "pending",
"starts_at_date": "2018-02-07",
"starts_at_time": "12:00",
"ends_at_date": "2018-02-07",
"ends_at_time": "12:00",
"description": "",
"ttype": "doctor",
"sum": 0,
"user": {
"id": 2,
"fullname": "Anna Palmgren"
},
"timetype": null,
"pause": 0,
"can_manage": true
}
]
}
]
I need it to be grouped on the name.
This is how I build the JSON object now.
json.array! [0,1] do |index|
if index == 0
json.total_entries #total
else
json.entries #events do |event|
json.extract! event, :id, :starts_at_date, :starts_at_time, :ends_at_date, :ends_at_time, :description, :ttype
json.sum event.sum
json.user event.user, :id, :fullname
json.can_manage true
end
end
end
Update
Should look like this more or less.
Marcus Lurem
Id
Status
starts_at_date
description
Anna Palmgren
Id
Status
starts_at_date
description
You can use something like this:
json.entries #events.group_by(&:user) do |user, events|
json.user :id, :fullname
json.events events do |event|
json.extract! event, :id, :starts_at_date, :starts_at_time, :ends_at_date, :ends_at_time, :description, :ttype
end
end

How to add search term to Spotify API

I am building an app using rails, angular, and RSpotify. I'm still kind of a newbie, and feel like the answer to my question is right in front of me, but I am struggling to figure it out.
After I authenticate a user, I redirect to a search to find new songs/albums/artist etc. Once they find relevant songs, they can add them to a playlist.
Using RSpotify, I can make the data to json, and then show that data using angular. Here is an example of what I am doing;
users_controller.rb
def music
music = RSpotify::Artist.search("Wiz Khalifa")
respond_to do |format|
format.json { render :json => music}
end
end
I added to my routes, and now this spits out some data;
localhost:3000/api/music.json
[
{
"genres": [],
"images": [
{
"height": 1200,
"url": "https://i.scdn.co/image/6fcf0a3556f9edf47f4d17c33a48418a3d2e6bce",
"width": 900
},
{
"height": 853,
"url": "https://i.scdn.co/image/d803a20e1402bf2c46353c97d929a3f28c27366e",
"width": 640
},
{
"height": 267,
"url": "https://i.scdn.co/image/0d706a776e505ad54968f389e4c6b820a7615562",
"width": 200
},
{
"height": 85,
"url": "https://i.scdn.co/image/534b45d0038ca0142b50dcc3f338a8fdd9caa949",
"width": 64
}
],
"name": "Wiz Khalifa",
"popularity": 91,
"top_tracks": {},
"external_urls": {
"spotify": "https://open.spotify.com/artist/137W8MRPWKqSmrBGDBFSop"
},
"href": "https://api.spotify.com/v1/artists/137W8MRPWKqSmrBGDBFSop",
"id": "137W8MRPWKqSmrBGDBFSop",
"type": "artist",
"uri": "spotify:artist:137W8MRPWKqSmrBGDBFSop"
},
{
"genres": [],
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/d4e1be09af57961ff630662daa5e44e75a99f18b",
"width": 640
},
{
"height": 300,
"url": "https://i.scdn.co/image/814960e7e3b52dc4b9985974e4b9f4e25e40860c",
"width": 300
},
{
"height": 64,
"url": "https://i.scdn.co/image/aa9543dd6a6fba6be98894c02141943da40cb81d",
"width": 64
}
],
"name": "Snoop Dogg & Wiz Khalifa",
"popularity": 34,
"top_tracks": {},
"external_urls": {
"spotify": "https://open.spotify.com/artist/3rnsFvKusYivCTnK2fpwbu"
},
"href": "https://api.spotify.com/v1/artists/3rnsFvKusYivCTnK2fpwbu",
"id": "3rnsFvKusYivCTnK2fpwbu",
"type": "artist",
"uri": "spotify:artist:3rnsFvKusYivCTnK2fpwbu"
},
{
"genres": [],
"images": [
{
"height": 600,
"url": "https://i.scdn.co/image/425f29c04ce8953339cac3b47e56dce53a82d396",
"width": 600
},
{
"height": 300,
"url": "https://i.scdn.co/image/7ea62fef2465095d3283843defd4daefb1a9b627",
"width": 300
},
{
"height": 64,
"url": "https://i.scdn.co/image/7f92197321b425d83b63ad3db550729fec74df9b",
"width": 64
}
],
"name": "BAyBOy Ft. Wiz Khalifa",
"popularity": 0,
"top_tracks": {},
"external_urls": {
"spotify": "https://open.spotify.com/artist/15qZ54HBDz6nDQKvafOKqG"
},
"href": "https://api.spotify.com/v1/artists/15qZ54HBDz6nDQKvafOKqG",
"id": "15qZ54HBDz6nDQKvafOKqG",
"type": "artist",
"uri": "spotify:artist:15qZ54HBDz6nDQKvafOKqG"
},
So, I am able to reach the data from spotify which is good. However, the call Artist.search takes a parameter. So my question is, using a search tab like this;
home.html.erb
<%= form_tag "/music" do %>
<%= label_tag :search %>
<%= text_field_tag :search %>
<%= submit_tag :search %>
<% end %>
How could I add user input from the search bar as the parameter for RSpotify::Artist.search()? Any help pointing me in the right direction is very appreciated. Thanks.
users_controller.rb
def music
#music = RSpotify::Artist.search(params[:search])
render :json => #music
end

Beautify JSON parsing with Hashie::Mash Rash?

Trying to parse some ugly JSON:
image = product.images.find { |i| i["sizeName"] == "Large" }
If I use Hashie::Mash Rash, can I make it look like this instead?
image = product.images.find { |i| i["size_name"] == "large" }
If so, why am I getting undefined method 'each_pair' for #<Array:0x007f84a0408540>? Please see https://gist.github.com/frankie-loves-jesus/6b8012f9197ca6c675a9 for a full example including a live app.
Example JSON:
{
"metadata": {
"category": {
"id": "women",
"name": "Women's Fashion"
},
"showSizeFilter": false,
"showColorFilter": true,
"offset": 0,
"limit": 20,
"total": 974184
},
"products": [
{
"id": 377083005,
"name": "BCBGeneration Women's Contrast Sleeve Trench",
"currency": "USD",
"price": 168,
"priceLabel": "$168.00",
"salePrice": 106.43,
"salePriceLabel": "$106.43",
"inStock": true,
"retailer": {
"id": "849",
"name": "Amazon.com",
"url": "http://www.shopstyle.com/browse/Amazon.com-US?pid=uid9616-726296-93"
},
"locale": "en_US",
"description": "This jacket features contrasting leather sleeves",
"brand": {
"id": "51",
"name": "BCBG MAX AZRIA",
"url": "http://www.shopstyle.com/browse/BCBG-MAX-AZRIA?pid=uid9616-726296-93"
},
"clickUrl": "http://api.shopstyle.com/action/apiVisitRetailer?id=377083005&pid=uid9616-726296-93",
"images": [
{
"sizeName": "Small",
"width": 32,
"height": 40,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a_small.jpg"
},
{
"sizeName": "Medium",
"width": 112,
"height": 140,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a_medium.jpg"
},
{
"sizeName": "Large",
"width": 164,
"height": 205,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a.jpg"
}
],
"colors": [
{
"name": "Chino"
}
],
"sizes": [
{
"name": "XX-Small"
},
{
"name": "X-Small"
}
],
"categories": [
{
"id": "raincoats-and-trenchcoats",
"name": "Raincoats & Trenchcoats"
}
]
}
]
}
This is my working code
require 'json'
require 'rash'
#json_text = <<END
{
"metadata": {
"category": {
"id": "women",
"name": "Women's Fashion"
},
"showSizeFilter": false,
"showColorFilter": true,
"offset": 0,
"limit": 20,
"total": 974184
},
"products": [
{
"id": 377083005,
"name": "BCBGeneration Women's Contrast Sleeve Trench",
"currency": "USD",
"price": 168,
"priceLabel": "$168.00",
"salePrice": 106.43,
"salePriceLabel": "$106.43",
"inStock": true,
"retailer": {
"id": "849",
"name": "Amazon.com",
"url": "http://www.shopstyle.com/browse/Amazon.com-US?pid=uid9616-726296-93"
},
"locale": "en_US",
"description": "This jacket features contrasting leather sleeves",
"brand": {
"id": "51",
"name": "BCBG MAX AZRIA",
"url": "http://www.shopstyle.com/browse/BCBG-MAX-AZRIA?pid=uid9616-726296-93"
},
"clickUrl": "http://api.shopstyle.com/action/apiVisitRetailer?id=377083005&pid=uid9616-726296-93",
"images": [
{
"sizeName": "Small",
"width": 32,
"height": 40,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a_small.jpg"
},
{
"sizeName": "Medium",
"width": 112,
"height": 140,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a_medium.jpg"
},
{
"sizeName": "Large",
"width": 164,
"height": 205,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a.jpg"
}
],
"colors": [
{
"name": "Chino"
}
],
"sizes": [
{
"name": "XX-Small"
},
{
"name": "X-Small"
}
],
"categories": [
{
"id": "raincoats-and-trenchcoats",
"name": "Raincoats & Trenchcoats"
}
]
}
]
}
END
hash = JSON.parse(#json_text)
#rash = Hashie::Rash.new( hash )
images = []
#rash.products.each do |product|
images << product.images.find { |i| i.size_name.downcase == "large" }
end
puts images.inspect
#[#<Hashie::Rash height=205 size_name="Large" url="http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a.jpg" width=164>]
It doesn't raise the error you have mentioned.
And I use
$ruby --version
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin13.0.0]
gem list --local |grep 'rash'
rash (0.4.0)
$gem list --local |grep 'hashie'
hashie (3.2.0, 2.0.5)
Could you check yours?
And, if possible, dump the json at the moment that it raises the error.

Resources