Zomato api how to get restaurant website url? - json

I am creating a react app and I am using Zomato api for restaurants. I was able to display the search results in the app and link to a single page with specific restaurant details. I wanted to fill up the single restaurant page with name, link to restaurant website, address, photo gallery, etc. I already have the rest of the info in the restaurant json. However. I couldn't find any info to link to the restaurant website. All I could find is several links to zomato page with info for the specific website and on this page, there's the link to the restaurant website...
Here's the specific restaurant json I got from zomato api:
R: {has_menu_status: {…}, res_id: 16935822}
all_reviews: {reviews: Array(3)}
all_reviews_count: 3
apikey: ""
average_cost_for_two: 30
book_again_url: ""
book_form_web_view_url: ""
cuisines: "Drinks Only"
currency: "$"
deeplink: "zomato://restaurant/16935822"
establishment: ["Lounge"]
events_url: "https://www.zomato.com/miami/blackbird-ordinary-downtown-miami/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"
featured_image: "https://b.zmtcdn.com/data/reviews_photos/607/4edc23f93d257fbed50f184d8c920607_1503580424.png?fit=around%7C640%3A640&crop=640%3A640%3B%2A%2C%2A"
has_online_delivery: 0
has_table_booking: 0
highlights: (15) ["Credit Card", "Lunch", "Serves Alcohol", "Cash", "Dinner", "Live Music", "Outdoor Seating", "Live Entertainment", "Fullbar", "Valet Parking Available", "Indoor Seating", "Nightlife", "Wine", "Serves Cocktails", "Street Parking"]
id: "16935822"
include_bogo_offers: true
is_book_form_web_view: 0
is_delivering_now: 0
is_table_reservation_supported: 0
is_zomato_book_res: 0
location: {address: "729 SW 1st Avenue, Downtown Miami, Miami 33130", locality: "Downtown Miami", city: "Miami", city_id: 291, latitude: "25.7667186000", …}
menu_url: "https://www.zomato.com/miami/blackbird-ordinary-downtown-miami/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop"
mezzo_provider: "OTHER"
name: "Blackbird Ordinary"
offers: []
opentable_support: 0
phone_numbers: "(305) 671-3307"
photo_count: 34
photos: (4) [{…}, {…}, {…}, {…}]
photos_url: "https://www.zomato.com/miami/blackbird-ordinary-downtown-miami/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop"
price_range: 3
switch_to_order_menu: 0
thumb: "https://b.zmtcdn.com/data/reviews_photos/607/4edc23f93d257fbed50f184d8c920607_1503580424.png?impolicy=newcropandfit&cropw=886&croph=886&cropoffsetx=169&cropoffsety=1&cropgravity=NorthWest&fitw=200&fith=200&fittype=ignore"
timings: "3 PM to 5 AM (Mon-Fri),5 PM to 5 AM (Sat-Sun)"
url: "https://www.zomato.com/miami/blackbird-ordinary-downtown-miami?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"
user_rating: {aggregate_rating: "3.3", rating_text: "Average", rating_color: "CDD614", rating_obj: {…}, votes: "14"}
__proto__: Object
I am begining to find out that I kinda don't like Zomato api, but it will take more time to switch over to something else....

Related

How to retrieve data from a json

I retrieved a dataset from a news API in JSON format. I want to extract the news description from the JSON data.
This is my code:-
import requests
import json
url = ('http://newsapi.org/v2/top-headlines?'
'country=us&'
'apiKey=608bf565c67f4d99994c08d74db82f54')
response = requests.get(url)
di=response.json()
di = json.dumps(di)
for di['articles'] in di:
print(article['title'])
The dataset looks like this:-
{'status': 'ok',
'totalResults': 38,
'articles': [
{'source':
{'id': 'the-washington-post',
'name': 'The Washington Post'},
'author': 'Derek Hawkins, Marisa Iati',
'title': 'Coronavirus updates: Texas, Florida and Arizona officials say early reopenings fueled an explosion of cases - The Washington Post',
'description': 'Local officials in states with surging coronavirus cases issued dire warnings Sunday about the spread of infections, saying the virus was rapidly outpacing containment efforts.',
'url': 'https://www.washingtonpost.com/nation/2020/07/05/coronavirus-update-us/',
'urlToImage': 'https://www.washingtonpost.com/wp-apps/imrs.php?src=https://arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/K3UMAKF6OMI6VF6BNTYRN77CNQ.jpg&w=1440',
'publishedAt': '2020-07-05T18:32:44Z',
'content': 'Here are some significant developments:\r\n<ul><li>The rolling seven-day average for daily new cases in the United States reached a record high for the 27th day in a row, climbing to 48,606 on Sunday, … [+5333 chars]'}])
Please guide me with this!
There are few corrections needed in your code.. below code should work and i have removed API KEY in answer make sure that you add one before testing
import requests
import json
url = ('http://newsapi.org/v2/top-headlines?'
'country=us&'
'apiKey=<API KEY>')
di=response.json()
#You don't need to dump json that is already in json format
#di = json.dumps(di)
#your loop is not correctly defined, below is correct way to do it
for article in di['articles']:
print(article['title'])
response.json
{'status': 'ok',
'totalResults': 38,
'articles': [
{'source':
{'id': 'the-washington-post',
'name': 'The Washington Post'},
'author': 'Derek Hawkins, Marisa Iati',
'title': 'Coronavirus updates: Texas, Florida and Arizona officials say early reopenings fueled an explosion of cases - The Washington Post',
'description': 'Local officials in states with surging coronavirus cases issued dire warnings Sunday about the spread of infections, saying the virus was rapidly outpacing containment efforts.',
'url': 'https://www.washingtonpost.com/nation/2020/07/05/coronavirus-update-us/',
'urlToImage': 'https://www.washingtonpost.com/wp-apps/imrs.php?src=https://arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/K3UMAKF6OMI6VF6BNTYRN77CNQ.jpg&w=1440',
'publishedAt': '2020-07-05T18:32:44Z',
'content': 'Here are some significant developments:\r\n<ul><li>The rolling seven-day average for daily new cases in the United States reached a record high for the 27th day in a row, climbing to 48,606 on Sunday, … [+5333 chars]'}]}
Code:
di = response.json() # Understand that 'di' is of type 'dictionary', key-value pair
for i in di["articles"]:
print(i["description"])
"articles" is one of the keys of dictionary di, It's corresponding value is of type list. "description" , which you are looking is part of this list (value of "articles"). Further list contains the dictionary (key-value pair).You can access from key - description

Altering JSON Structure

So I am using a webscraper to pull information on sneakers from a website. The son data that comes back is structured like so
[
{
"web-scraper-order": "1554084909-97",
"web-scraper-start-url": "https://www.goat.com/sneakers",
"productlink": "$200AIR JORDAN 6 RETRO 'INFRARED' 2019",
"productlink-href": "https://www.goat.com/sneakers/air-jordan-6-retro-black-infrared-384664-060",
"name": "Air Jordan 6 Retro 'Infrared' 2019",
"price": "Buy New - $200",
"description": "The 2019 edition of the Air Jordan 6 Retro ‘Infrared’ is true to the original colorway, which Michael Jordan wore when he captured his first NBA title. Dressed primarily in black nubuck with a reflective 3M layer underneath, the mid-top features Infrared accents on the midsole, heel tab and lace lock. Nike Air branding adorns the heel and sockliner, an OG detail last seen on the 2000 retro.",
"releasedate": "2019-02-16",
"colorway": "Black/Infrared 23-Black",
"brand": "Air Jordan",
"designer": "Tinker Hatfield",
"technology": "Air",
"maincolor": "Black",
"silhouette": "Air Jordan 6",
"nickname": "Infrared",
"category": "lifestyle",
"image-src": "https://image.goat.com/crop/1250/attachments/product_template_additional_pictures/images/018/675/318/original/464372_01.jpg.jpeg"
},
{
"web-scraper-order": "1554084922-147",
"web-scraper-start-url": "https://www.goat.com/sneakers",
"productlink": "$190YEEZY BOOST 350 V2 'CREAM WHITE / TRIPLE WHITE'",
"productlink-href": "https://www.goat.com/sneakers/yeezy-boost-350-v2-cream-white-cp9366",
"name": "Yeezy Boost 350 V2 'Cream White / Triple White'",
"price": "Buy New - $220",
"description": "First released on April 29, 2017, the Yeezy Boost 350 V2 ‘Cream White’ combines a cream Primeknit upper with tonal cream SPLY 350 branding, and a translucent white midsole housing full-length Boost. Released again in October 2018, this retro helped fulfill Kanye West’s oft-repeated ‘YEEZYs for everyone’ Twitter mantra, as adidas organized the biggest drop in Yeezy history by promising pre-sale to anyone who signed up on the website. Similar to the first release, the ‘Triple White’ 2018 model features a Primeknit upper, a Boost midsole and custom adidas and Yeezy co-branding on the insole.",
"releasedate": "2017-04-29",
"colorway": "Cream White/Cream White/Core White",
"brand": "adidas",
"designer": "Kanye West",
"technology": "Boost",
"maincolor": "White",
"silhouette": "Yeezy Boost 350",
"nickname": "Cream White / Triple White",
"category": "lifestyle",
"image-src": "https://image.goat.com/crop/1250/attachments/product_template_additional_pictures/images/014/822/695/original/116662_03.jpg.jpeg"
},
However, I want to change it so that the top level node is sneakers and the next level down would be a specific sneaker brand ( Jordan, Nike, Adidas) and then the list of sneakers that belong to that brand. So my JSON structure would look something like this
Sneakers {
Adidas :{
[shoe1,
shoe2,
....
] },
Jordan: {
[shoe1,
shoe2,
....
]
}
}
I am not sure what tool I could use to do that. Any help would be greatly appreciated. All I have at the moment is the JSON file and it is not in the structure that I want it to be in.
One way of doing this would be to populate a dict whose keys are brand names and their values are lists of sneaker records. Assuming that data is your original list, here's the code:
sneakers_by_brand = {}
for record in data:
if sneakers_by_brand.get(record.get("brand")):
sneakers_by_brand[record.get("brand")].append(record)
else:
sneakers_by_brand[record.get("brand")] = [record]
print(sneakers_by_brand)

Why my angular.forEach loop isn't working

I am not sure what's going wrong, cause it looks pretty straight forward to me. I have few things in my mind about appending the JSON response, but for that when I am trying to apply forEach loop to my Json , no data is shown in the alert
Angular code
mainApp.controller('MultiCarouselController', function($scope, $http) {
$scope.products = [];
$http.get("/get_broad_category_products/?BroadCategory=BroadCategory3")
.success(function (response) {
$scope.products = response;
angular.forEach(products,function(value,key){
alert(key+'----'+value); // can see this alerts
});
}).error(function(){
console.log('Error happened ... ');
});
});
My JSON response is some junk data of Products
[
{
"sku": "d1cd71a8-9dc5-4724-b269-473ede28a1d7",
"selectedQtyOptions": [],
"selectedSize": "",
"description": "foolish interpolates trumpet monographs ferried inboards Forster tike grammatically sunroof vaporizing Sweden demure retouching completely robbing readies unloose guiltless tatty unobservant cuffs fortieth wither rigorously paradoxically snowmobiling charts clenching planning dealing lesions bicameral pertly chaffinches grumpiness private purled insanely attainment proposal Fatima execrates pshaws chars actuators turboprop soughed kicking majors conquistadores Cynthia septuagenarians kneecaps titans attractions larvas invigorating trunking Shevat recluse Trina slenderness kinking falsified logistically hogged skyrocketing ordinal avoiding trademarked underfoot garter sacrificial pricey nosedive bachelors deiced heave dictatorial muffing prayed rewinding recopied limpidly Crichton conversion chitterlings signets Aiken Froissart turnoff snowshoe forded spiralled underwriters flourishes Sade splicer transfusions cesspools lifelike ruckus showering paean voguish Buck copings Russell watchdog magneto pored height zodiac motherland backings Venus obeys scooters nonintervention dinosaur unashamedly anathema hibernate consumerism portended worked mystically existentialist dissatisfies badgers unanimously triplicated Jenny sagacity Windex snoopier nonplusing shovelling Assam putty darn Sulawesi Italians gunnery codify develops rhinos upwards Louise welled experiences socks pinky mewed Camille claimants swirl squattest ware parenthetic bonitoes hydrangeas decolonizing omit skyjacks Gorky financiers province flywheel southeastward Bayeux updated yowl Tulsidas macintosh sprees pralines systolic uncommoner cilium tromping Asimov heinous cordoned combated camerawomen syndrome identified prizefights heavyweight vertically reflector integrity Hebrides sepulchral loner parrot smooths candidness",
"selectedQty": "1",
"title": "viragoes",
"brand": "Brand0",
"images": [
{
"image0": "/media/products/f791a316ced7b3b774bd61e138197224.jpg"
}
],
"sizeQtyPrice": [
{
"discountAttributes": "chinos theosophy misdemeanor irrigates school Pullman sombrely suspect vortex baddest",
"measureUnit": "ltr",
"discountPercent": 4,
"mrp": 3102,
"qty": 7,
"size": 66
},
{
"discountAttributes": "Molotov absurd traces pounces contracts clarions thighbone Hesse parricide constrains",
"measureUnit": "m",
"discountPercent": 16,
"mrp": 2773,
"qty": 7,
"size": 18
},
{
"discountAttributes": "detainment gunnysack vied expropriation unobtrusive collectables embracing poster hexing governess",
"measureUnit": "m",
"discountPercent": 6,
"mrp": 9920,
"qty": 6,
"size": 69
}
],
"id": 9
},
{
"sku": "838660bb-7ab9-4f2a-8be7-9602a5801756",
"selectedQtyOptions": [],
"selectedSize": "",
"description": "agreeing vizier bleariest trig appliquéing copulating commissariats Balzac lunchtimes glittery quacking Leoncavallo heehawing Tampax lizards pegged nanosecond centigrade subplots tumbrils give jawed skits nickel discontinues impinged evangelized Platonist waterlines dams symposiums intercessor cognition heavier softener dromedaries bravos immobilize consciously Clemons patch klutzier Kirkpatrick caddying designs Dulles twelfths undemocratic isolationists infected ma homering soliciting minibus pluralism fraternity catalyzed Scorpio pandemonium waxwing starter infuses rebuttals spirals rerunning interrogatories Manuel whomsoever tenderized conjoint baronesses callower parenthetic plusses extend cockier Fokker dewlap Cowper Swammerdam secs hock relaxations Judas Canadian presidency lo wildness Philippe picture beekeeper lull manuals transnational yaw chloroformed perennials distinctive Nottingham antiquaries underneath parted nervously basemen observatories scrubbed encoder egalitarians winnow caddish Hawaiians brownstones robbing exhaustible antagonist benefactresses Plasticine Peace platypi Guzman stippled shuts peacemakers butterfly Bolton grout McCain Lebanon bounce oleander Balkans endearments snowfall spoonerisms furnaces inequities billowy jutting guffaw beautifully penis newtons snuffboxes j Angelita tinkles literature depicts insouciant scribblers blinker disobediently devotees primordial sixties Kalamazoo shear contest classes cripple edging exactest cheat invocation thrived drunkenness Fuller architectures sprite Lillian constricts tucking chastisements walruses guzzlers rejoinder apprenticeships pillory spendthrift omens spoonful contortions precociously intensely motorway guts cahoot sculptor paralytics reminisce meltdown trusts lady pronghorn scurried Campbell micron flawing foals nigher",
"selectedQty": "1",
"title": "smokier",
"brand": "Brand2",
"images": [
{
"image0": "/media/products/f51a649e72694d23962ee77a97872f0e.jpg"
}
],
"sizeQtyPrice": [
{
"discountAttributes": "Beerbohm earldom Stanley seconding hypertension Sayers miserly epitome retires ditching",
"measureUnit": "m",
"discountPercent": 15,
"mrp": 5065,
"qty": 6,
"size": 83
},
{
"discountAttributes": "confine Newman bagel cornflower rears generator goaded midweeks drain cigarillo",
"measureUnit": "Kg",
"discountPercent": 12,
"mrp": 2284,
"qty": 9,
"size": 13
},
{
"discountAttributes": "eerier fizzes lessened rotisserie developer Gray industrial callused convergences ampoule",
"measureUnit": "gms",
"discountPercent": 4,
"mrp": 6816,
"qty": 8,
"size": 18
}
],
"id": 14
}
]
products isn't defined. It should be $scope.products

Parsing JSON data from Yelp API

I'm new to programming and am trying to parse some data returned from Yelp's API. From this data, how could I return something like just the phone number (display_phone) and address? Thank you
Result for business "little-miss-bbq-phoenix-2" found:
{ u'categories': [[u'Barbeque', u'bbq']],
u'display_phone': u'+1-602-437-1177',
u'id': u'little-miss-bbq-phoenix-2',
u'image_url': u'http://s3-media2.fl.yelpcdn.com/bphoto/4Rcm0IIbRhdo-4Z4KPvuXQ/ms.jpg',
u'is_claimed': True,
u'is_closed': False,
u'location': { u'address': [u'4301 E University Dr'],
u'city': u'Phoenix',
u'coordinate': { u'latitude': 33.421587,
u'longitude': -111.989088},
u'country_code': u'US',
u'display_address': [ u'4301 E University Dr',
u'Phoenix, AZ 85034'],
u'geo_accuracy': 9.5,
u'postal_code': u'85034',
u'state_code': u'AZ'},
u'mobile_url': u'http://m.yelp.com/biz/little-miss-bbq-phoenix-2',
u'name': u'Little Miss BBQ',
u'phone': u'6024371177',
u'rating': 5.0,
u'rating_img_url': u'http://s3-media1.fl.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png',
u'rating_img_url_large': u'http://s3-media3.fl.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png',
u'rating_img_url_small': u'http://s3-media1.fl.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png',
u'review_count': 403,
u'reviews': [ { u'excerpt': u"I saw that this place had almost 400 reviews and that they have a perfect 5 star rating. It sounded too good to be true BUT it's worth every star and...",
u'id': u'-9poa0ycpVnOveVlqbYE9Q',
u'rating': 5,
u'rating_image_large_url': u'http://s3-media3.fl.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png',
u'rating_image_small_url': u'http://s3-media1.fl.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png',
u'rating_image_url': u'http://s3-media1.fl.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png',
u'time_created': 1431095420,
u'user': { u'id': u'd43iQ50HjWIl4vN4rBgoVQ',
u'image_url': u'http://s3-media4.fl.yelpcdn.com/photo/sn17KBbRjXOEELnjSir1tg/ms.jpg',
u'name': u'Jason J.'}}],
u'snippet_image_url': u'http://s3-media4.fl.yelpcdn.com/photo/sn17KBbRjXOEELnjSir1tg/ms.jpg',
u'snippet_text': u"I saw that this place had almost 400 reviews and that they have a perfect 5 star rating. It sounded too good to be true BUT it's worth every star and...",
u'url': u'http://www.yelp.com/biz/little-miss-bbq-phoenix-2'}

Invalid Json Error in JsonLint

I have a web service returning following json:
[
{
"id": "9469",
"title": "A person grabbed by police because being Nigerian he was carrying a Ghanaian passport!",
"introtext": "A person has grabbed by police because being Nigerian he was having a Ghanaian passport!
An individual has gotten by police on the grounds that being Nigerian he was having a Ghanaian visa!
A 29-year-old Nigerian has been captured for endeavoring to get a visa with a falsely acquired Ghanaian travel permit."
}
]
JSONLint is giving following error:
Parse error on line 5:
... "introtext": "A person has grabbe
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
I am really unable to understand what is making json invalid here? Is it newline or what? What can I do to make it work? Thanks.
New line present in introtex, this is valid json check it
[
{
"id": "9469",
"title": "A person grabbed by police because being Nigerian he was carrying a Ghanaian passport!",
"introtext": "A person has grabbed by police because being Nigerian he was having a Ghanaian passport! An individual has gotten by police on the grounds that being Nigerian he was having a Ghanaian visa! A 29-year-old Nigerian has been captured for endeavoring to get a visa with a falsely acquired Ghanaian travel permit."
}
]
Put your whole string in one line.
example
[
{
"id": "9469",
"title": "A person grabbed by police because being Nigerian he was carrying a Ghanaian passport!",
"introtext": "A person has grabbed by police because being Nigerian he was having aGhanaian passport! An individual has gotten by police on the grounds that being Nigerian he was having a Ghanaian visa! A 29-year-old Nigerian has been captured for endeavoring to get a visa with a falsely acquired Ghanaian travel permit."
}
]
In case you want line break use
"introtext": "A person has grabbed by police because \n being Nigerian he was having aGhanaian passport! An individual has gotten by police on the grounds that being Nigerian he was having a Ghanaian visa! A 29-year-old Nigerian has been captured for endeavoring to get a visa with a falsely acquired Ghanaian travel permit."
Thanks to #MONTYHS and #AvinashGarg for pointing out the mistake. Newline is causing invalid JSON. To have break lines in my json, I am replacing all newline tags <br/> with a special character, e.g. |~ (bar and a tilde). At client side, after parsing json, I replace occurrences of |~ with <br/> back to display properly.
Hope it helps someone. Reference is here.