Openweathermap API Forecast accessing array - arrays

So I'm trying to mess around with the openweathermap API and I can't figure out how to access some of the data.
Here the snippet of code I have that access the API.
public void find_forecast () {
String url = "http://api.openweathermap.org/data/2.5/forecast?id=4466033&appid=e4c641dd837c7947a127972091185dad&units=imperial";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("list");
JSONObject object = array.getJSONObject(1);
String description = object.getString("dt");
day1.setText(description);
Here is a snippet of the API code:
{
"cod": "200",
"message": 0.0042,
"cnt": 40,
"list": [
{
"dt": 1524614400,
"main": {
"temp": 63.77,
"temp_min": 63.77,
"temp_max": 64.26,
"pressure": 1017.45,
"sea_level": 1021.4,
"grnd_level": 1017.45,
"humidity": 97,
"temp_kf": -0.27
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
So as you can see the code above will return the value of dt which is 1524614400. But I'm trying to access for example under "weather" the "description" which in this case is light rain. I guess I don't know how to access an array inside an array, although I couldn't even get the "temp" to return under "main", although I could get "main" to return everything underneath it.
Thanks for any help.
Max

Not sure about Android but in Javascript I would try this:
var dataObj = {
"cod": "200",
"message": 0.0042,
"cnt": 40,
"list": [
{
"dt": 1524614400,
"main": {
"temp": 63.77,
"temp_min": 63.77,
"temp_max": 64.26,
"pressure": 1017.45,
"sea_level": 1021.4,
"grnd_level": 1017.45,
"humidity": 97,
"temp_kf": -0.27
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
]
}
]
}
console.log(dataObj.list[0].weather[0].description);

I finally figured this out. Code is below!
String array = response.getJSONArray("list").getJSONObject(0).getJSONArray("weather").getJSONObject(0).getString("description");
day1.setText(array);
This will return light rain from the API code above.

Related

ReactJS data from API

Hello guys when i'm running this code in ReactJS
const callApi = async () => {
const response = await axios.get('http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=mykey');
setWeather(response)
}
i can get to console.log(weather.data) but when i try to get console.log(weather.data.main)
i get this error TypeError: Cannot read property 'main' of undefined i tried to parse that data to JSON but that didnt work either.
Here you can see that this object has this property:
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04n"
}
],
"base": "stations",
"main": {
"temp": 12.43,
"feels_like": 7.81,
"temp_min": 11.67,
"temp_max": 13,
"pressure": 1010,
"humidity": 62
},
.....other items
}
Thank you for all answers.
Sometimes during the first render data isn't defined yet so use:
console.log(weather.data?.main)
and works like a if(data)

Calling parse function in swift fails

I am working on a food delivery app, which uses parse as its backend. I am facing a problem while calling the placeOrder API through
PFCloud.callFunction(inBackground: PlaceOrder, withParameters: params) { (data, err) in}
Please have a look at the JSON which I need to post below.
{
"source": "card_1EVYuOEynlyM6L4SHgBMJYRQ",
"userId": "YjSZYSXEp7",
"data": {
"menuItems": [{
"id": "QSYa2JDcIm",
"title": "Rice With Tibss(Beef)",
"menuTitle": "Rice With Tibss",
"submenuItem": [{
"id": "zaOo6G4KSV",
"name": "Beef",
"price": 12,
"desc": "Fillings?"
}],
"price": 24,
"qty": 1,
"storeId": "yqBCDmzaDP",
"storeName": "Ibex Ethiopian Cusine and Bar",
"orderType": "takeout",
"taxState": 0.0925,
"storeInfo": {
"cart_storeId": "yqBCDmzaDP",
"cart_storeName": "Ibex Ethiopian Cusine and Bar",
"cart_storeImage": "https://res.cloudinary.com/http-get-tolofood-com/image/upload/c_scale,h_199,q_auto,w_270/v1461575640/Ibex_lopx38.jpg",
"cart_storeCuisine": "Ethiopian",
"cart_storeDescription": "We always serve a quality food. We always serve a quality food. We always serve a quality food. We always serve a quality food.",
"cart_storeRating": 3.33,
"cart_storeDelivery": false,
"takeout": true,
"address": "12255 Greenville Ave,Dallas, TX 75243",
"slugname": "TX_DAL_ibex_ethiopian_cuisine_and_bar",
"multiple_location": false,
"cart_storeDeliveryFee": 15,
"cart_storeServes": "Lunch,Dinner",
"busy": false,
"cart_storeSeoSlug": "ibex-ethiopian-cusine-and-bar"
},
"enable": true,
"voice_read_mi_label": "fbgcb",
"voice_read_mi_option": false,
"menuTypeName": "Standard"
}],
"lastOrderType": "takeout",
"searchedAddress": "takeout",
"timeData": {
"day": "06-05-2019",
"time": "12:55 am",
"tz": "America/Los_Angeles"
}
},
"unavailable_option": "restaurant_recommendation"
}
And below is the Swift code which I have used to make pass it.
let storeInfo: Dictionary = [CartStoreId: self.cartStoreId, CartStoreName: self.cartRestaurantName, CartStoreImage: self.cartStoreImage, CartStoreCuisine: self.cartStoreCuisine, CartStoreDescription: self.cartStoreDescription, CartStoreRating: self.cartStoreRating, CartStoreDelivery: self.cartStoreDelivery, Takeout: self.takeOut, Address: self.address, Slugname: self.slugName, MultipleLocation: self.multipleLocation, CartStoreDeliveryFee: self.cartStoreDelivery, CartStoreServes: self.cartStoreServes, Busy: self.busy, CartStoreSeoSlug: self.cartStoreSeoSlug] as Dictionary
let subMenuItem = ["id": "zaOo6G4KSV", "name": "Beef", "price": 12, "desc": "Fillings?", "voice_read_submi_label":"bf", "voice_read_submi_option":false, "disabled": false] as [String: Any]
let ordersDictionary = [
"id" : "1234",
"title" : "Test",
"menuTitle" : "MenuName",
"price" : 23,
"qty" : 2,
"storeId" : 23,
"orderType" : "standard",
"taxState" : 0.22,
"enable" : true,
"menuTypeName" : "Type Name",
"voice_read_mi_label":"fdfs",
"voice_read_mi_option":"false",
"submenuitem": subMenuItem,
"storeInfo": storeInfo
] as Dictionary
let timeData = ["day" : 17-06-2019, "time": "11:00 AM", "tz": "America/Los_Angeles"] as Dictionary
let data = ["menuItems": ordersDictionary, "lastOrderType": "takeout", "searchedAddress": "takeout", "timeData" : timeData] as Dictionary
let params = [UserId: self.userId, "source":"card_1EVYuOEynlyM6L4SHgBMJYRQ", "data": data, "unavailable_option":"restaurant_recommendation","_ApplicationId":"6EuadToYoFGJhI1sX8XnuFBz9tp9l3yH6HxzzXZO", "_JavaScriptKey":"rQkALu9saFtF2oq9yCibyw6mEcs3PVqct3uuP6vg", "_ClientVersion":"js1.6.14", "_InstallationId":"444ec64d-5fcc-7b8e-596e-6be627892c2a",
"_SessionToken":"r:c966376120c8eca77aa63c29d5bebe1a"] as Dictionary
After all this is done I call the parse function like below.
PFCloud.callFunction(inBackground: PlaceOrder, withParameters: params) { (data, err) in
if err != nil {
print(err!)
} else {
print(data!)
}
}
But this gives me error after a few seconds saying
"Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}"
I have searched the web with the error and made fixes accordingly but still no success. Please help me guys.
I noticed that your params var is not compatible with the JSON you sent, there are more fields and also missing fields. Moreover, menuItems and submenuItem are an Array in your JSON and an Object in your code. It is probably making the cloud code function to fail and you are therefore not receiving back a valid JSON. Try the following and check if it works. In the case it works, just replace the values by your vars.
let params = [
"source": "card_1EVYuOEynlyM6L4SHgBMJYRQ",
"userId": "YjSZYSXEp7",
"data": [
"menuItems": [[
"id": "QSYa2JDcIm",
"title": "Rice With Tibss(Beef)",
"menuTitle": "Rice With Tibss",
"submenuItem": [[
"id": "zaOo6G4KSV",
"name": "Beef",
"price": 12,
"desc": "Fillings?"
]],
"price": 24,
"qty": 1,
"storeId": "yqBCDmzaDP",
"storeName": "Ibex Ethiopian Cusine and Bar",
"orderType": "takeout",
"taxState": 0.0925,
"storeInfo": [
"cart_storeId": "yqBCDmzaDP",
"cart_storeName": "Ibex Ethiopian Cusine and Bar",
"cart_storeImage": "https://res.cloudinary.com/http-get-tolofood-com/image/upload/c_scale,h_199,q_auto,w_270/v1461575640/Ibex_lopx38.jpg",
"cart_storeCuisine": "Ethiopian",
"cart_storeDescription": "We always serve a quality food. We always serve a quality food. We always serve a quality food. We always serve a quality food.",
"cart_storeRating": 3.33,
"cart_storeDelivery": false,
"takeout": true,
"address": "12255 Greenville Ave,Dallas, TX 75243",
"slugname": "TX_DAL_ibex_ethiopian_cuisine_and_bar",
"multiple_location": false,
"cart_storeDeliveryFee": 15,
"cart_storeServes": "Lunch,Dinner",
"busy": false,
"cart_storeSeoSlug": "ibex-ethiopian-cusine-and-bar"
],
"enable": true,
"voice_read_mi_label": "fbgcb",
"voice_read_mi_option": false,
"menuTypeName": "Standard"
]],
"lastOrderType": "takeout",
"searchedAddress": "takeout",
"timeData": [
"day": "06-05-2019",
"time": "12:55 am",
"tz": "America/Los_Angeles"
]
],
"unavailable_option": "restaurant_recommendation"
]

Decode the encoded value directly in view/html

I am submitting a form for job posting and have skills like C# which escape in my rest API. So I encoded the skills and sending to backend.
"skills":encodeURIComponent(skills)
now when I get back the skills I am doing decodeURIComponent for my skills
$scope.skills = decodeURIComponent(skills);
but this wont work with array of datas, when I want to fetch list of jobs , the datas comes in array , my array has almost 15 key values , which will be used in table some way. Writing a new array and pushing each values into array again pushing decoded skills a big process.
Is any solution to directly decoded the value in view , that is html
I tried {{decodeURIComponent(item.skills) }} but no luck.
sample Data ::
{
"json": {
"response": {
"statusmessage": "Success",
"count": 59,
"data": [
{
"employerId": 2,
"employerEmail": "sumit#infosoftjoin.in",
"employerName": "SumitKumar",
"companyName": "Infosoftjoin%20pvt%20ltd.",
"jobId": 142,
"jobTitle": "Test%20case%201",
"jobDescription": "<p>ahdu%29%28#*%29*W%29%28*%29E%26%3D--%3D</p>",
"link": "http://www.infosoftjoin.in",
"numberOfPositions": 5,
"createdTime": "18-May-2018",
"lastUpdatedTime": "18-May-2018",
"consumedCredits": 44,
"location": {
"city": "North And Middle Andaman",
"state": "Andaman and Nicobar Islands",
"country": "India"
},
"skills": [
"C%23.NET"
],
"approved": 1,
"status": "Approved"
},
{
"employerId": 2,
"employerEmail": "sumit#infosoftjoin.in",
"employerName": "SumitKumar",
"companyName": "Infosoftjoin%20pvt%20ltd.",
"jobId": 130,
"jobTitle": "New%20job",
"jobDescription": "hryuyurfkituo8",
"link": "http://www.infosoftjoin.in",
"numberOfPositions": 5,
"createdTime": "16-May-2018",
"lastUpdatedTime": "16-May-2018",
"consumedCredits": 93,
"location": {
"city": "Nicobar",
"state": "Andaman and Nicobar Islands",
"country": "India"
},
"skills": [
"APACHE TOMCAT"
],
"approved": 1,
"status": "Approved"
}
]
}
}
}
encodeURIComponent is a JavaScript built-in function, you can not access it directly in your AngularJs template. Convert that into a $scope function then try accessing from AngularJs template.
I would suggest you to have a filter for the same instead of $scope function.
Filter:
app.filter('decodeFilter', function() {
return function(input) {
return decodeURIComponent(input);
};
});
Template:
{{item.skills | decodeFilter}}
If still you want that as $scope function then try below code:
Controller:
$scope.decodeComponent=function(value){
return decodeURIComponent(value);
}
Template:
{{decodeComponent(item.skills)}}
Also, please check this plunker for sample scenario with the above examples.

Node.JS - How to access Values of Dictionary within an Array of a Key in a Dictionary?

I'm new in Node.JS and I'm able to parse the JSON data and do a console log to print out name and badges.
var details = JSON.parse(body);
console.log(details.name, details.badges.length);
But I don't know how I can get the data inside the arrays of the bagdes such as id, name, url.
I tried
console.log(details.badges.length.id);
But nothing shows up. How can I access that? Thank you.
{
"name": "Andrew Chalkley",
"badges": [
{
"id": 49,
"name": "Newbie",
"url": "http:\/\/teamtreehouse.com\/chalkers",
"icon_url": "https:\/\/achievement-images.teamtreehouse.com\/Generic_Newbie.png",
"earned_date": "2012-07-23T19:59:34.000Z",
"courses": [
]
},
{
"id": 26,
"name": "Introduction",
"url": "http:\/\/teamtreehouse.com\/library\/html\/introduction",
"icon_url": "https:\/\/achievement-images.teamtreehouse.com\/HTML_Basics.png",
"earned_date": "2012-07-23T21:57:24.000Z",
"courses": [
{
"title": "HTML",
"url": "http:\/\/teamtreehouse.com\/library\/html",
"badge_count": 1
},
{
"title": "Introduction",
"url": "http:\/\/teamtreehouse.com\/library\/html\/introduction",
"badge_count": 1
}
]
}
}
It is an array, so you need the index, for example: details.badges[0].id
This will return the first (index 0) element id.
.length only returns the length of the array, so it will not be useful to get the data in it.

Twitter search api entities with media not working with Json.net for Windows phone Mango silverlight

Below is my returned json from twitter
{
"created_at": "Sat, 11 Feb 2012 06:38:28 +0000",
"entities": {
"hashtags": [
{
"text": "Shubhdin",
"indices": [
9,
18
]
}
],
"urls": [],
"user_mentions": [
{
"screen_name": "SAMdLaw",
"name": "Sabyasachi Mohapatra",
"id": 104420398,
"id_str": "104420398",
"indices": [
0,
8
]
}
]
},
"from_user": "nilayshah80",
"from_user_id": 213599118,
"from_user_id_str": "213599118",
"from_user_name": "Nilay Shah",
"geo": {
"coordinates": [
18.6003,
73.825
],
"type": "Point"
},
"id": 168222351106899968,
"id_str": "168222351106899968",
"iso_language_code": "in",
"metadata": {
"result_type": "recent"
},
"profile_image_url": "http://a2.twimg.com/profile_images/1528184590/IMG_0465_normal.JPG",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1528184590/IMG_0465_normal.JPG",
"source": "<a href="http://twabbit.wordpress.com/" rel="nofollow">twabbit</a>",
"text": "#SAMdLaw #Shubhdin mitra",
"to_user": "SAMdLaw",
"to_user_id": 104420398,
"to_user_id_str": "104420398",
"to_user_name": "Sabyasachi Mohapatra",
"in_reply_to_status_id": 168219865197461505,
"in_reply_to_status_id_str": "168219865197461505"
},
{
"created_at": "Sun, 12 Feb 2012 01:54:07 +0000",
"entities": {
"hashtags": [
{
"text": "IWIllAlwaysLoveYou",
"indices": [
88,
107
]
}
],
"urls": [],
"user_mentions": [],
"media": [
{
"id": 168513175187238912,
"id_str": "168513175187238912",
"indices": [
108,
128
],
"media_url": "http://p.twimg.com/Alat1wsCMAAh-wE.jpg",
"media_url_https": "https://p.twimg.com/Alat1wsCMAAh-wE.jpg",
"url": "http://shortener.twitter.com/dRc4dXH3",
"display_url": "pic.twitter.com/dRc4dXH3",
"expanded_url": "http://twitter.com/RIPWhitneyH/status/168513175183044608/photo/1",
"type": "photo",
"sizes": {
"orig": {
"w": 395,
"h": 594,
"resize": "fit"
},
"large": {
"w": 395,
"h": 594,
"resize": "fit"
},
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 340,
"h": 511,
"resize": "fit"
},
"medium": {
"w": 395,
"h": 594,
"resize": "fit"
}
}
}
]
},
"from_user": "RIPWhitneyH",
"from_user_id": 19319043,
"from_user_id_str": "19319043",
"from_user_name": "RIP Whitney Houston",
"geo": null,
"id": 168513175183044608,
"id_str": "168513175183044608",
"iso_language_code": "en",
"metadata": {
"recent_retweets": 8,
"result_type": "popular"
},
"profile_image_url": "http://a2.twimg.com/profile_images/1820957590/images__13__normal.jpg",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1820957590/images__13__normal.jpg",
"source": "<a href="http://twitter.com/">web</a>",
"text": "R-T if you think that the Grammy's should organize an \"R.I.P. Whitney Houston\" tribute. #IWIllAlwaysLoveYou http://shortener.twitter.com/dRc4dXH3",
"to_user": null,
"to_user_id": null,
"to_user_id_str": null,
"to_user_name": null
},
If you noticed Media under entities not available in above 2 and when i tried to call below snippet gives me null reference error
MediaUrl = (from user in tweet["entities"]["media"]
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList()
Same code work for Entities/URL, Hashtags and mentions but not for Media.
Also tried this -> Get JSON object node but still getting null reference exception.
In first tweet, entities object doesn't have media property, so when evaluating first tweet, your code would be equivalent to :
MediaUrl = (from user in (IEnumerable<JToken>)null
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList()
which will throw ArgumentNullException because that code does query on null reference collection.
Finally got working. Not appropriate solution but works for me.
I created separate method for parsing Media. Passed Entity as string and in that method i checked is EntityString.Contains Media or not. If yes, then parse media json else returned null. See below Snippet.
if (Entities != string.Empty)
{
if (Entities.Contains("\"media\":"))
{
JObject searchResult = JObject.Parse(Entities);
returnMedia = (from user in searchResult["media"]
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList();
}
}
This works for me. If you have any better solution then Please let me know.

Resources