How to parsing the following weather api in jquery [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I want to parse the Weather API (URL) city name, temperature, etc.
My JSON data is the following:
{
"data": {
"current_condition": [{
"cloudcover": "25",
"humidity": "70",
"observation_time": "04:21 PM",
"precipMM": "0.3",
"pressure": "1007",
"temp_C": "30",
"temp_F": "86",
"visibility": "4",
"weatherCode": "113",
"weatherDesc": [{
"value": "Clear"}],
"weatherIconUrl": [{
"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0008_clear_sky_night.png"}],
"winddir16Point": "S",
"winddirDegree": "180",
"windspeedKmph": "7",
"windspeedMiles": "4"}],
"request": [{
"query": "Ahmedabad, India",
"type": "City"}],
"weather": [{
"date": "2012-09-18",
"precipMM": "2.1",
"tempMaxC": "32",
"tempMaxF": "89",
"tempMinC": "25",
"tempMinF": "76",
"weatherCode": "176",
"weatherDesc": [{
"value": "Patchy rain nearby"}],
"weatherIconUrl": [{
"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0009_light_rain_showers.png"}],
"winddir16Point": "SSW",
"winddirDegree": "203",
"winddirection": "SSW",
"windspeedKmph": "12",
"windspeedMiles": "8"},
{
"date": "2012-09-19",
"precipMM": "3.4",
"tempMaxC": "32",
"tempMaxF": "89",
"tempMinC": "25",
"tempMinF": "76",
"weatherCode": "176",
"weatherDesc": [{
"value": "Patchy rain nearby"}],
"weatherIconUrl": [{
"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0009_light_rain_showers.png"}],
"winddir16Point": "SW",
"winddirDegree": "223",
"winddirection": "SW",
"windspeedKmph": "12",
"windspeedMiles": "7"}]
}
}​
How do I parse this data and get city name and temperature..I have no idea..Thanks in adavance.
=============== OutPut =======================
i want to fetch data like this and Set on Textbox
Date 2012-09-18 2012-09-19
tempMaxC 32 32
tempMinC 25 25
tempMaxF 89 89
tempMinF 76 76

If you've retrieved this JSON as a string, then pass this string to JSON.parse()* and then access to retrieved value as to a regular JavaScript object:
var jsonStr = '{ "data": { "current_condition": [ {"cloudcover": "25", "humidity": "70", "observation_time": "04:21 PM", "precipMM": "0.3", "pressure": "1007", "temp_C": "30", "temp_F": "86", "visibility": "4", "weatherCode": "113", "weatherDesc": [ {"value": "Clear" } ], "weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0008_clear_sky_night.png" } ], "winddir16Point": "S", "winddirDegree": "180", "windspeedKmph": "7", "windspeedMiles": "4" } ], "request": [ {"query": "Ahmedabad, India", "type": "City" } ], "weather": [ {"date": "2012-09-18", "precipMM": "2.1", "tempMaxC": "32", "tempMaxF": "89", "tempMinC": "25", "tempMinF": "76", "weatherCode": "176", "weatherDesc": [ {"value": "Patchy rain nearby" } ], "weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0009_light_rain_showers.png" } ], "winddir16Point": "SSW", "winddirDegree": "203", "winddirection": "SSW", "windspeedKmph": "12", "windspeedMiles": "8" }, {"date": "2012-09-19", "precipMM": "3.4", "tempMaxC": "32", "tempMaxF": "89", "tempMinC": "25", "tempMinF": "76", "weatherCode": "176", "weatherDesc": [ {"value": "Patchy rain nearby" } ], "weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0009_light_rain_showers.png" } ], "winddir16Point": "SW", "winddirDegree": "223", "winddirection": "SW", "windspeedKmph": "12", "windspeedMiles": "7" } ] }}',
jsonObj = JSON.parse(jsonStr);
console.log(jsonObj.data.current_condition[0].temp_F);
Otherwise, if you've retrieved this JSON e.g. as a parameter of some jQuery $.ajax() success callback and it's already an object, you don't need to call JSON.parse(), but just retrieve object's values directly:
$.getJSON("http://example.com/weather.json", function(jsonObj) {
// The response string is already parsed with $.parseJSON(),
// so you don't need to parse it yourself.
// Therefore just go ahead and access the properties of JavaScript object.
console.log(jsonObj.data.current_condition[0].temp_F);
});
* If you're intended to support older browsers (e.g. IE7) that does not support JSON.parse/stringify, you'll need to include JSON library.
UPDATE:
DEMO for particular case

Related

Javascript extract value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm using weather-js with this code :
weather.find({search: 'San Francisco, CA', degreeType: 'F'}, function(err, result) {
if(err) console.log(err);
console.log(JSON.stringify(result, null, 2));
});
But I don't know how I could extract the result value from this
The result should be like this:
[
{
"location": {
"name": "San Francisco, CA",
"lat": "37.777",
"long": "-122.42",
"timezone": "-7",
"alert": "",
"degreetype": "F",
"imagerelativeurl": "http://blob.weather.microsoft.com/static/weather4/en-us/"
},
"current": {
"temperature": "70",
"skycode": "32",
"skytext": "Sunny",
"date": "2017-03-14",
"observationtime": "13:15:00",
"observationpoint": "San Francisco, California",
"feelslike": "70",
"humidity": "59",
"winddisplay": "3 mph West",
"day": "Tuesday",
"shortday": "Tue",
"windspeed": "3 mph",
"imageUrl": "http://blob.weather.microsoft.com/static/weather4/en-us/law/32.gif"
},
"forecast": [
{
"low": "52",
"high": "69",
"skycodeday": "31",
"skytextday": "Clear",
"date": "2017-03-13",
"day": "Monday",
"shortday": "Mon",
"precip": ""
},
{
"low": "52",
"high": "70",
"skycodeday": "34",
"skytextday": "Mostly Sunny",
"date": "2017-03-14",
"day": "Tuesday",
"shortday": "Tue",
"precip": "10"
},
{
"low": "56",
"high": "63",
"skycodeday": "26",
"skytextday": "Cloudy",
"date": "2017-03-15",
"day": "Wednesday",
"shortday": "Wed",
"precip": "20"
},
{
"low": "50",
"high": "64",
"skycodeday": "28",
"skytextday": "Mostly Cloudy",
"date": "2017-03-16",
"day": "Thursday",
"shortday": "Thu",
"precip": "10"
},
{
"low": "53",
"high": "67",
"skycodeday": "32",
"skytextday": "Sunny",
"date": "2017-03-17",
"day": "Friday",
"shortday": "Fri",
"precip": "10"
}
]
}
]
In the result, there are many useful information:
latitude & longitude of the location
current temperature of the location
forecast information for next four days
All those information exist in the result JSON that you can parse and use it. Consider that the result is an JSON array with only one element in this case.
for example you can log current temperature like this:
console.log(result[0].current.temperature)
Declare a variable and write the result into this variable, if no error occured:
var res = null;
weather.find({search: 'San Francisco, CA', degreeType: 'F'}, function(err, result) {
if(err) {
console.log(err);
} else {
res = result;
}
console.log(JSON.stringify(result, null, 2));
});

How do I filter an object that is part of an array value?

Given the following data
[
{
"date": "2017-10-04",
"games": [
{
"notes": "Game was played",
"time": "2017-10-04T20:24:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "10",
"game_id": 1
},
{
"notes": "Game was played",
"time": "2017-10-04T12:35:30+00:00",
"sport": "lacrosse",
"owner": "steve",
"players": "6",
"game_id": 2
},
{
"notes": "Game was played",
"time": "2017-10-04T10:12:30+00:00",
"sport": "hockey",
"owner": "henry",
"players": "10",
"game_id": 4
}
]
},
{
"date": "2017-10-14",
"games": [
{
"notes": "Game was played",
"time": "2017-10-14T20:32:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "4",
"game_id": 3
},
{
"notes": "Game was played",
"time": "2017-10-14T20:34:30+00:00",
"sport": "soccer",
"owner": "john",
"players": "12",
"game_id": 5
}
]
}
]
how do I filter out the objects so that I only show the hockey games played on that date. Essentially I need the same array of objects back, but the object should only be shown if the games key = sport: hockey
I know I can only run the filter method on arrays, but I can't figure out how to loop over the object inside of the array and return the whole object again. Any help would be greatly appreciated.
Try:
const filtered = yourArray.map(item => ({...item, games: item.games.filter(game => game.sport === 'hockey')})
// When run, this produces:
[
{
"date": "2017-10-04",
"games": [
{
"game_id": 1,
"notes": "Game was played",
"owner": "steve",
"players": "10",
"sport": "hockey",
"time": "2017-10-04T20:24:30+00:00"
},
{
"game_id": 4,
"notes": "Game was played",
"owner": "henry",
"players": "10",
"sport": "hockey",
"time": "2017-10-04T10:12:30+00:00"
}
]
},
{
"date": "2017-10-14",
"games": [
{
"game_id": 3,
"notes": "Game was played",
"owner": "steve",
"players": "4",
"sport": "hockey",
"time": "2017-10-14T20:32:30+00:00"
}
]
}
]
Which I think is what you want.
I think the following code should do the trick:
var x=[
{
"date": "2017-10-04",
"games": [
{
"notes": "Game was played",
"time": "2017-10-04T20:24:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "10",
"game_id": 1
},
{
"notes": "Game was played",
"time": "2017-10-04T12:35:30+00:00",
"sport": "lacrosse",
"owner": "steve",
"players": "6",
"game_id": 2
},
{
"notes": "Game was played",
"time": "2017-10-04T10:12:30+00:00",
"sport": "hockey",
"owner": "henry",
"players": "10",
"game_id": 4
}
]
},
{
"date": "2017-10-14",
"games": [
{
"notes": "Game was played",
"time": "2017-10-14T20:32:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "4",
"game_id": 3
},
{
"notes": "Game was played",
"time": "2017-10-14T20:34:30+00:00",
"sport": "soccer",
"owner": "john",
"players": "12",
"game_id": 5
}
]
}]
function filterByDate (data, date){
return data.filter(function(entry){
return sameDay(new Date(entry.date), date)
})
}
function filterBySport(data, sport){
data.forEach(function(entry){
entry.games=entry.games.filter(function(entry2){
return entry2.sport===sport
})
})
return data
}
function sameDay(date1, date2){ //helper function to check for date equality
return date1.getFullYear()===date2.getFullYear() &&
date1.getMonth()===date2.getMonth() &&
date1.getDay()===date2.getDay()
}
function myFilter(data, date, sportType){ // the final function you have to call
return filterBySport(filterByDate(data, date), sportType)
}
console.log(myFilter(x, new Date("2017-10-04"), "hockey"))
Let's take an array :-
let students = [
{"Name": "Priya","marks": [50, 60, 70, 80, 90]},
{"Name": "Ankita","marks": [80, 90, 95]}
]
Now, I want to filter marks greater than or equal to 90, The code will look like this.
students.map((student) => {
return {...student,
marks: student.marks.filter((mark) => mark >= 90)
}
})
// Result will be [{"Name": "Priya", "marks": [90]}, {"Name": "Ankita","marks": [90,95]}]
Spread operator will expand student and then it will override the marks key with filtered marks value.
If you will not use spread operator,
students.map((student) => student.marks.filter((mark) => mark >= 90))
// Result will be [[90],[90]]
Then you will get only the filtered values and not the values on which you haven't applied the filter.

Typescript model class for JSON object

I have the following JSON:
{
"-KtDGS8GdOcJ33Lcqjok": {
"2017": {
"address": "test address 1",
"area2": "3212",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Solar",
"client": "Test Contact",
"createdAt": 1504551753483,
"lastEdited": 1504551805648,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.490362758827665",
"lng": "-69.93279173970221",
"name": "17002 - test",
"pictures": {
"a95ff256-0f05-3122-a6b5-a88d3fd14c3f": true
},
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "1234",
"year": "2017"
}
},
"-KtDGaU9BB6eNj-MsyBg": {
"2015": {
"address": "test 2a",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504552100747,
"lastEdited": 1504552100747,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "15002 - test2a ",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2015"
},
"2017": {
"address": "test 2",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504551790632,
"lastEdited": 1504551790632,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "17003 - test2b",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2017"
}
},
"codeCounter": {
"2015": 2,
"2017": 5
},
"totals": {
"2015": 1,
"2017": 5
}
}
It's basically a list of objects, each object contains one or more nested objects wrapped in the year they were made (physically these are houses,apartments, etc.).
Where I'm having trouble is trying to map the 'year' objects (2017, 2015, etc') as they may or may not exist. For example, an object may have both 2017, 2016 entries or only one of them, etc.
I already have a 'Property' model class that I believe works, it has all the address, author, category, etc. fields. I'm trying to create the outter class that would contain a list of these property objects:
export interface PropertyWrapper {
[year: number]: Property;
}
I tried parsing the JSON as a PropertyWrapper[] array and this way I can already access a property by calling:
for (const pw of data) {
console.log(pw[2017]);
}
But this only works because I already know the object has a '2017' entry. How could I do this dynamically regardless of whether or not there's a '2017', '2010', or 10 entries ?
Are you looking for something like this.
First gets object keys, then loop through these keys and then loop through nested object keys
var jso = {
"-KtDGS8GdOcJ33Lcqjok": {
"2017": {
"address": "test address 1",
"area2": "3212",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Solar",
"client": "Test Contact",
"createdAt": 1504551753483,
"lastEdited": 1504551805648,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.490362758827665",
"lng": "-69.93279173970221",
"name": "17002 - test",
"pictures": {
"a95ff256-0f05-3122-a6b5-a88d3fd14c3f": true
},
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "1234",
"year": "2017"
}
},
"-KtDGaU9BB6eNj-MsyBg": {
"2015": {
"address": "test 2a",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504552100747,
"lastEdited": 1504552100747,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "15002 - test2a ",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2015"
},
"2017": {
"address": "test 2",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504551790632,
"lastEdited": 1504551790632,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "17003 - test2b",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2017"
}
},
"codeCounter": {
"2015": 2,
"2017": 5
},
"totals": {
"2015": 1,
"2017": 5
}
};
Object.keys(jso).forEach(function(key) {
Object.keys(jso[key]).forEach(function(nestedKey){
console.log(`nestedKey: ${nestedKey} \n ` , jso[key][nestedKey]);
});
});

Parsing JSON data efficiently into front end list

I have been browsing for the past 2 days and can't seem to find an answer to this anywhere.
I am using PHP to parse all of my SQL data into a JSON format here is an example of the JSON:
[
{
"id": "1",
"name": "Jim",
"age": "39",
"address": "12 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "1",
"canWorkNights": "1",
"isStudent": "1"
},
{
"id": "2",
"name": "Fred",
"age": "29",
"address": "13 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "1",
"canWorkNights": "1",
"isStudent": "0"
},
{
"id": "3",
"name": "Bill",
"age": "19",
"address": "14 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "1",
"canWorkNights": "0",
"isStudent": "0"
},
{
"id": "4",
"name": "Tom",
"age": "39",
"address": "15 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "0",
"canWorkNights": "0",
"isStudent": "0"
},
{
"id": "5",
"name": "Cathy",
"age": "29",
"address": "16 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "0",
"canWorkNights": "0",
"isStudent": "1"
},
{
"id": "6",
"name": "Petra",
"age": "19",
"address": "17 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "0",
"canWorkNights": "1",
"isStudent": "0"
},
{
"id": "7",
"name": "Heide",
"age": "39",
"address": "18 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "1",
"canWorkNights": "0",
"isStudent": "0"
},
{
"id": "8",
"name": "William",
"age": "29",
"address": "19 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "1",
"canWorkNights": "0",
"isStudent": "1"
},
{
"id": "9",
"name": "Ted",
"age": "19",
"address": "20 High Street, London",
"hasCar": "0",
"speaksForeignLanguage": "0",
"canWorkNights": "0",
"isStudent": "1"
},
{
"id": "10",
"name": "Mike",
"age": "19",
"address": "21 High Street, London",
"hasCar": "1",
"speaksForeignLanguage": "0",
"canWorkNights": "0",
"isStudent": "1"
},
{
"id": "11",
"name": "Jo",
"age": "19",
"address": "22 High Street, London",
"hasCar": "0",
"speaksForeignLanguage": "1",
"canWorkNights": "0",
"isStudent": "1"
}
]
That is just an example and isn't the actual data I am using, my JSON data contains 8 image image links for each row and contains more string data.
I need to list up to 120 records on the front end, this list will have filtered search options.
When the client visits the search page I am guessing they will need to load all of the JSON data which would probably cause a slow user experience.
Is there anyway JSON data can be loaded on request so the client doesn't need to load all of that data at once? So for example maybe only request the data for 10 records per page so the whole JSON file isn't loaded?
Any advice would be great.
You can use local storage. Should be something like this:
// your json data
var json = {};
// you have store it as string
localStorage.setItem("data", JSON.stringify(json));
Then in the page you need it, just get it like this:
var data = localStorage.getItem("data");
// if the "data" key isn't set on the storage, it returns null
if (data != null)
{
// now deserialize the string to json
data = JSON.parse(data);
}
The local storage is available in all major browsers versions, as you can see here.

calculate the date diff in javascript from JSON array

I have a JSON object which returns a list of events with dates and times, I want to add a counter to the next event time, but i am not sure how to approach this?
Basically, my JSON is like:
[{"name": "BAKER-CROSSROADS", "country": "USA", "lon": "165.25", "yield": "21", "lat": "11.58", "depth": ".027", "date": "1946/07/24 21:35:00", "id": "1"}, {"name": "VENUS", "country": "USA", "lon": "-116.2", "yield": "10", "lat": "37.19", "depth": ".03", "date": "1958/02/22 01:00:00", "id": "10", "fill": "green"}, {"name": "HATCHIE", "country": "USA", "lon": "-116.03", "yield": "20", "lat": "37.058", "depth": ".061", "date": "1963/02/08 16:00:01", "id": "100", "fill": "green"}, {"name": "CLIMAX:Upshot-Knothole", "country": "USA", "lon": "-116.0183", "yield": "61", "lat": "37.0875", "depth": "-.41", "date": "1953/06/04 11:14:57", "id": "1000", "fill": "red"}, {"name": "BRAVO:Castle", "country": "USA", "lon": "165.274", "yield": "15000", "lat": "11.698", "depth": "0", "date": "1954/02/28 18:45:00", "id": "1001", "fill": "red"}, ....
so for each object:
{"name": "BAKER-CROSSROADS", "country": "USA", "lon": "165.25", "yield": "21", "lat": "11.58", "depth": ".027", "date": "1946/07/24 21:35:00", "id": "1"}
{"name": "VENUS", "country": "USA", "lon": "-116.2", "yield": "10", "lat": "37.19", "depth": ".03", "date": "1958/02/22 01:00:00", "id": "10", "fill": "green"}
...
here is the code that reads the json file:
this.loadNext = function () {
d3.json("./data/detonations.json", function(datum) {
for(var i = datum.length - 1; i >= 0; --i) {
var o = datum[i];
//console.log(o);
message = {
country: o.country
,date: o.date
,depth: o.depth
,lon: o.lon
,lat: o.lat
,type: o.type
,yield: o.yield
};
self.doSomething(message)
}
});
}
i would like to calculate the date/time difference, so in this case the difference of "1958/02/22 01:00:00" and "1946/07/24 21:35:00" and pass this to the message array?
To have this difference in millisecondes, you may use
var diff = (new Date(s2)).getTime() - (new Date(s1)).getTime();
That's because the format you have is directly parsable by the Date class.

Categories

Resources