Il ressemble à tout votre code est en train de faire est en fin de compte ceci:
require 'json'
def mine_location
client = Yelp::Client.new
request = Yelp::Review::Request::GeoPoint.new(latitude: 13.3125,
longitude: -6.2468, yws_id: 'nicetry')
response = client.search(request)
return response['businesses'].to_json
end
Ce qui fonctionne très bien pour moi.
Si, pour une raison ou une autre, vous devez vraiment écrire votre propre implémentation d'un émetteur JSON, voici quelques conseils pour vous. Le numéro 1 que vous ignorez complètement dans votre code est que Ruby est un langage orienté objet, plus spécifiquement un langage orienté objet basé sur la classe. Cela signifie que les problèmes sont résolus en construisant un réseau d'objets qui communiquent les uns avec les autres via le passage de messages et en répondant à ces messages en exécutant des méthodes définies dans les classes auxquelles ces objets appartiennent. Cela nous donne beaucoup de puissance: répartition dynamique, polymorphisme, encapsulation et une tonne d'autres. Tirer parti ceux-ci, votre émetteur de JSON ressemblerait à quelque chose comme ceci:
class Object
def to_json; to_s end
end
class NilClass
def to_json; 'null' end
end
class String
def to_json; %Q'"#{to_s}"' end
end
class Array
def to_json; "[#{map(&:to_json).join(', ')}]" end
end
class Hash
def to_json; "{#{map {|k, v| "#{k.to_json}: #{v.to_json}" }.join(', ')}}" end
end
mine_location
regarde comme ci-dessus, à l'exception évidemment sans la partie require 'json'
.
Si vous voulez que votre JSON bien formaté, vous pouvez essayer quelque chose comme ceci:
class Object
def to_json(*) to_s end
end
class String
def to_json(*) inspect end
end
class Array
def to_json(indent=0)
"[\n#{' ' * indent+=1}#{
map {|el| el.to_json(indent) }.join(", \n#{' ' * indent}")
}\n#{' ' * indent-=1}]"
end
end
class Hash
def to_json(indent=0)
"{\n#{' ' * indent+=1}#{
map {|k, v|
"#{k.to_json(indent)}: #{v.to_json(indent)}"
}.join(", \n#{' ' * indent}")
}\n#{' ' * indent-=1}}"
end
end
Il y a en fait rien Ruby spécifique dans ce code. C'est à peu près exactement à quoi ressemblerait la solution dans n'importe quel autre langage orienté objet basé sur une classe comme Java, par exemple. C'est juste un design orienté objet 101.
La seule chose qui est spécifique au langage est de savoir comment "modifier" les classes et leur ajouter des méthodes. En Ruby ou Python, vous modifiez littéralement la classe. En C# et Visual Basic.NET, vous utiliseriez probablement des méthodes d'extension, dans Scala vous utiliseriez des conversions implicites et en Java peut-être le Pattern Design Pattern.
Un autre énorme problème avec votre code est que vous essayez de résoudre un problème qui est évidemment récursive sans jamais réellement récursion. Ce juste ne peut pas travailler. Le code que vous avez écrit est fondamentalement du code Fortran-57: procédural sans objets et sans récursion. Même simplement déplacer un cran au dessus de Fortran, disons, Pascal, vous donne une belle solution procédurale récursive:
def jsonify(o)
case o
when Hash
"{#{o.map {|k, v| "#{jsonify(k)}: #{jsonify(v)}" }.join(', ')}}"
when Array
"[#{o.map(&method(:jsonify)).join(', ')}]"
when String
o.inspect
when nil
'null'
else
o.to_s
end
end
Bien sûr, vous pouvez jouer le même jeu avec des indentations ici:
def jsonify(o, indent=0)
case o
when Hash
"{\n#{' ' * indent+=1}#{
o.map {|k, v|
"#{jsonify(k, indent)}: #{jsonify(v, indent)}"
}.join(", \n#{' ' * indent}") }\n#{' ' * indent-=1}}"
when Array
"[\n#{' ' * indent+=1}#{
o.map {|el| jsonify(el, indent) }.join(", \n#{' ' * indent}") }\n#{' ' * indent-=1}]"
when String
o.inspect
when nil
'null'
else
o.to_s
end
end
est ici la sortie de échancré puts mine_location
, produit en utilisant soit la deuxième version (en retrait) de to_json
ou la deuxième version de jsonify
, il ne compte pas vraiment, ils ont tous deux la même sortie:
[
{
"name": "Nickies",
"mobile_url": "http://mobile.yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ",
"city": "San Francisco",
"address1": "466 Haight St",
"zip": "94117",
"latitude": 37.772201,
"avg_rating": 4.0,
"address2": "",
"country_code": "US",
"country": "USA",
"address3": "",
"photo_url_small": "http://static.px.yelp.com/bpthumb/mPNTiQm5HVqLLcUi8XrDiA/ss",
"url": "http://yelp.com/biz/nickies-san-francisco",
"photo_url": "http://static.px.yelp.com/bpthumb/mPNTiQm5HVqLLcUi8XrDiA/ms",
"rating_img_url_small": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_small_4.png",
"is_closed": false,
"id": "yyqwqfgn1ZmbQYNbl7s5sQ",
"nearby_url": "http://yelp.com/search?find_loc=466+Haight+St%2C+San+Francisco%2C+CA",
"state_code": "CA",
"reviews": [
{
"rating": 3,
"user_photo_url_small": "http://static.px.yelp.com/upthumb/ZQDXkIwQmgfAcazw8OgK2g/ss",
"url": "http://yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ#hrid:t-sisM24K9GvvYhr-9w1EQ",
"user_url": "http://yelp.com/user_details?userid=XMeRHjiLhA9cv3BsSOazCA",
"user_photo_url": "http://static.px.yelp.com/upthumb/ZQDXkIwQmgfAcazw8OgK2g/ms",
"rating_img_url_small": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_small_3.png",
"id": "t-sisM24K9GvvYhr-9w1EQ",
"text_excerpt": "So I know gentrification is supposed to be a bad word and all (especially here in SF), but the Lower Haight might benefit a bit from it. At least, I like...",
"user_name": "Trey F.",
"mobile_uri": "http://mobile.yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ?srid=t-sisM24K9GvvYhr-9w1EQ",
"rating_img_url": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_3.png"
},
{
"rating": 4,
"user_photo_url_small": "http://static.px.yelp.com/upthumb/Ghwoq23_alkaXawgqj7dBA/ss",
"url": "http://yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ#hrid:8xTNOC9L5ZXwGCMNYY-pdQ",
"user_url": "http://yelp.com/user_details?userid=4F2QG3adYIUNXplqqp9ylA",
"user_photo_url": "http://static.px.yelp.com/upthumb/Ghwoq23_alkaXawgqj7dBA/ms",
"rating_img_url_small": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_small_4.png",
"id": "8xTNOC9L5ZXwGCMNYY-pdQ",
"text_excerpt": "This place was definitely a great place to chill. The atmosphere is very non-threatening and very neighborly. I thought it was cool that they had a girl dj...",
"user_name": "Jessy M.",
"mobile_uri": "http://mobile.yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ?srid=8xTNOC9L5ZXwGCMNYY-pdQ",
"rating_img_url": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_4.png"
},
{
"rating": 5,
"user_photo_url_small": "http://static.px.yelp.com/upthumb/q0POOE3vv2LzNg1qN8MMyw/ss",
"url": "http://yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ#hrid:pp33WfN_FoKlQKJ-38j_Ag",
"user_url": "http://yelp.com/user_details?userid=FmcKafW272uSWXbUF2rslA",
"user_photo_url": "http://static.px.yelp.com/upthumb/q0POOE3vv2LzNg1qN8MMyw/ms",
"rating_img_url_small": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_small_5.png",
"id": "pp33WfN_FoKlQKJ-38j_Ag",
"text_excerpt": "Love this place! I've been here twice now and each time has been a great experience. The bartender is so nice. When we had questions about the drinks he...",
"user_name": "Scott M.",
"mobile_uri": "http://mobile.yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ?srid=pp33WfN_FoKlQKJ-38j_Ag",
"rating_img_url": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_5.png"
}
],
"phone": "4152550300",
"neighborhoods": [
{
"name": "Hayes Valley",
"url": "http://yelp.com/search?find_loc=Hayes+Valley%2C+San+Francisco%2C+CA"
}
],
"rating_img_url": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_4.png",
"longitude": -122.429926,
"categories": [
{
"name": "Dance Clubs",
"category_filter": "danceclubs",
"search_url": "http://yelp.com/search?find_loc=466+Haight+St%2C+San+Francisco%2C+CA&cflt=danceclubs"
},
{
"name": "Lounges",
"category_filter": "lounges",
"search_url": "http://yelp.com/search?find_loc=466+Haight+St%2C+San+Francisco%2C+CA&cflt=lounges"
},
{
"name": "American (Traditional)",
"category_filter": "tradamerican",
"search_url": "http://yelp.com/search?find_loc=466+Haight+St%2C+San+Francisco%2C+CA&cflt=tradamerican"
}
],
"state": "CA",
"review_count": 32,
"distance": 1.87804019451141
}
]
Tout le monde n'a pas accès à l'API Yelp. Pourriez-vous fournir des exemples de données afin que nous puissions tester nos exemples améliorés? Y at-il quelque chose comme un compte de test, un compte factice, un faux compte ou une fausse API pour Yelp? –
Trouvé une réponse d'échantillon: http://Yelp.Com/developers/documentation/search_api#sampleResponse –
Bien sûr, il s'avère que l'exemple de réponse JSON sur le site de documentation de Yelp n'est même pas valide JSON ... –