I have a project I’m working on but I know very little about Javascript/Jquery/Ajax and am having trouble figuring out exactly what I need to do and don’t really have anyone around me to ask. Using the JSON info below, I need to include an Ajax call to populate current 'condition.temp’, the returned 'temperature' unit, and set the weather to be linked to 'link' key in the returned response. I’d like to return it to the console. I have it set up to return all of the JSON data to the console, but am stuck on how to return just the particular data items I need.
{
"success": true,
"data": [
{
"units": {
"distance": "mi",
"speed": "mph",
"pressure": "in",
"temperature": "F"
},
"language": "en-us",
"description": "Yahoo! Weather for Paducah, KY, US",
"astronomy": {
"sunrise": "5:45 am",
"sunset": "7:57 pm"
},
"item": {
"forecast": [
{
"day": "Mon",
"text": "Mostly Cloudy",
"date": "16 May 2016",
"high": 61,
"low": 47,
"code": 28
},
{
"day": "Tue",
"text": "Scattered Showers",
"date": "17 May 2016",
"high": 62,
"low": 51,
"code": 39
},
{
"day": "Wed",
"text": "Scattered Showers",
"date": "18 May 2016",
"high": 66,
"low": 50,
"code": 39
},
{
"day": "Thu",
"text": "Mostly Cloudy",
"date": "19 May 2016",
"high": 71,
"low": 51,
"code": 28
},
{
"day": "Fri",
"text": "Showers",
"date": "20 May 2016",
"high": 73,
"low": 58,
"code": 11
},
{
"day": "Sat",
"text": "Scattered Thunderstorms",
"date": "21 May 2016”,
"high": 74,
"low": 61,
"code": 47
},
{
"day": "Sun",
"text": "Partly Cloudy",
"date": "22 May 2016”,
"high": 76,
"low": 59,
"code": 30
},
{
"day": "Mon",
"text": "Partly Cloudy",
"date": "23 May 2016”,
"high": 81,
"low": 61,
"code": 30
},
{
"day": "Tue",
"text": "Thunderstorms",
"date": "24 May 2016",
"high": 81,
"low": 64,
"code": 4
},
{
"day": "Wed",
"text": "Rain",
"date": "25 May 2016",
"high": 82,
"low": 67,
"code": 12
}
],
"lat": 37.030182,
"guid": {
"isPermaLink": false
},
"condition": {
"text": "Cloudy",
"date": "Mon, 16 May 2016 03:00 PM CDT",
"temp": 60,
"code": 26
},
"description": "<![CDATA[<img src=\"http://l.yimg.com/a/i/us/we/52/26.gif\"/>\n<BR />\n<b>Current Conditions:</b>\n<BR />Cloudy\n<BR />\n<BR />\n<b>Forecast:</b>\n<BR /> Mon - Mostly Cloudy. High: 61Low: 47\n<BR /> Tue - Scattered Showers. High: 62Low: 51\n<BR /> Wed - Scattered Showers. High: 66Low: 50\n<BR /> Thu - Mostly Cloudy. High: 71Low: 51\n<BR /> Fri - Showers. High: 73Low: 58\n<BR />\n<BR />\nFull Forecast at Yahoo! Weather\n<BR />\n<BR />\n(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)\n<BR />\n]]>",
"link": "http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-12775789/",
"pubDate": "Mon, 16 May 2016 03:00 PM CDT",
"long": -88.712601,
"title": "Conditions for Paducah, KY, US at 03:00 PM CDT"
},
"image": {
"link": "http://weather.yahoo.com",
"height": 18,
"url": "http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif",
"width": 142,
"title": "Yahoo! Weather"
},
"ttl": 60,
"atmosphere": {
"visibility": 16.1,
"humidity": 60,
"pressure": 1007,
"rising": 0
},
"location": {
"country": "United States",
"city": "Paducah",
"region": " KY"
},
"link": "http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-12775789/",
"lastBuildDate": "Mon, 16 May 2016 04:35 PM CDT",
"wind": {
"direction": 105,
"chill": 59,
"speed": 7
},
"title": "Yahoo! Weather - Paducah, KY, US"
}
]
}
Assuming that you're asking how to extract data from JSON...
If you use the node console, you can dig into it and see the inner workings.
first, assign the json data to a variable, ie
var test = {
"success": true,
"data": [
{
"units": {
"distance": "mi",
"speed": "mph",
"pressure": "in",
"temperature": "F"
},
"language": "en-us", etc....
then start digging down the data using console.log:
> console.log(test);
{ success: true,
data:
[ { units: [Object],
language: 'en-us',
description: 'Yahoo! Weather for Paducah, KY, US',
So, how do we access "success"? This worked:
> console.log(test['success']);
true
But there is a better way:
> console.log(test.success);
true
Now, how do we get the "data" attributes?
> console.log(test.data);
[ { units: { distance: 'mi', speed: 'mph', pressure: 'in', temperature: 'F' },
language: 'en-us',
description: 'Yahoo! Weather for Paducah, KY, US',
astronomy: { sunrise: '5:45 am', sunset: '7:57 pm' },
item:
{ forecast: [Object],
lat: 37.030182,
we could try this:
> console.log(test.data.units);
undefined
Uh, oh... what happened? Short answer, data is an array ( [ )
> console.log(test.data[0].units);
{ distance: 'mi', speed: 'mph', pressure: 'in', temperature: 'F' }
Let's go one more:
> console.log(test.data[0].units.speed);
mph
Using this method you can extract any information out of JSON.
Related
I need help to extract data from this JSON file using jq.
The app flv then verify the streamname mystrame is active and extract meta.video.height
I did try lot of queries without success and my jq knowledge is poor.
{
"port": 1935,
"server_index": 0,
"applications": [{
"name": "hls",
"live": {
"streams": [{
"name": "donbosco",
"time": 2380739,
"bw_in": 2112440,
"bytes_in": 541618713,
"bw_out": 0,
"bytes_out": 0,
"bw_audio": 35544,
"bw_video": 2076888,
"clients": [{
"id": 453,
"address": "127.0.0.1",
"time": 2380959,
"flashver": "FMLE/3.0 (compatible; Lavf57.83.100)",
"dropped": 0,
"avsync": 28,
"timestamp": 2382635,
"publishing": true,
"active": true
}],
"records": [],
"meta": {
"video": {
"width": 1168,
"height": 720,
"frame_rate": 25,
"codec": "H264",
"profile": "High",
"level": 3.1
},
"audio": {
"codec": "AAC",
"profile": "LC",
"channels": 2,
"sample_rate": 16000
}
},
"nclients": 1,
"publishing": true,
"active": true
}],
"nclients": 1
},
"recorders": {
"count": 0,
"lists": []
}
},
{
"name": "flv",
"live": {
"streams": [{
"name": "mystream",
"time": 2382811,
"bw_in": 2059096,
"bytes_in": 541841549,
"bw_out": 2059096,
"bytes_out": 543351459,
"bw_audio": 35472,
"bw_video": 2023624,
"clients": [{
"id": 452,
"address": "127.0.0.1",
"time": 2382727,
"flashver": "LNX 9,0,124,2",
"dropped": 0,
"avsync": -12,
"timestamp": 2384520,
"publishing": false,
"active": true
},
{
"id": 451,
"address": "127.0.0.1",
"time": 2383031,
"flashver": "FMLE/3.0 (compatible; Lavf58.74.100)",
"dropped": 0,
"avsync": -12,
"timestamp": 2384520,
"publishing": true,
"active": true
}
],
"records": [],
"meta": {
"video": {
"width": 1168,
"height": 720,
"frame_rate": 25,
"codec": "H264",
"profile": "High",
"level": 3.1
},
"audio": {
"codec": "AAC",
"profile": "LC",
"channels": 2,
"sample_rate": 16000
}
},
"nclients": 2,
"publishing": true,
"active": true
}],
"nclients": 2
},
"recorders": {
"count": 0,
"lists": []
}
}
]
}
Are you asking for help with the command-line JSON processor jq or the JavaScript library jQuery? They are not the same. For jq, try
jq '
.applications
| map(select(.name == "flv"))[].live.streams
| map(select(.name == "mystream" and .active))[].meta.video.height
'
720
Demo
Hoping for some pointers here as I'm striking out with my attempts. Am working with python 3.8.5.
I'm querying a Car Park booking system that returns a json list of availability. The result has lots of nested dictionaries and I'm struggling to extract just the values i want.
This is what I've been doing:
import requests
import json
enquiry = requests.post(url.....) #queries api, this works fine
results = enquiry.text #extracts response data
dictionary = json.loads(results) #convert response to python dict
If there is one slot available, I get this output (apologies for length). If there are multiple slots available, i get the same output repeated:
{
"data": {
"services": [{
"id": null,
"name": null,
"services": [{
"id": null,
"name": "Car Park",
"met": true,
"filterCount": 1,
"primary": true,
"options": [{
"id": "9",
"images": [],
"available": true,
"calendarId": "AAAA",
"templateId": "BBBB",
"capacity": 0,
"name": "Car Park Slot 3",
"sessionId": "CCCC",
"functions": null,
"startDate": "2020-08-18T13:30:00Z", <--this is what I want to extract
"endDate": "2020-08-18T14:30:00Z",
"geo": {
"lat": 0.0,
"lng": 0.0
},
"selected": false,
"linkedServices": [],
"tiers": null
}]
}],
"currentBookingId": null,
"startDate": {
"ms": 1597757400000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 14,
"days": 0
}
},
"endDate": {
"ms": 1597761000000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 15,
"days": 0
}
},
"sessionId": "2222222",
"chargeType": 1,
"hasPrimaryBookable": false,
"hasBookable": false,
"hasDiscounts": false,
"hasMultipleTiers": false,
"isPreferred": false,
"primaryServiceAvailable": true,
"primaryServiceId": null,
"primaryServiceType": "undefined",
"unavailableAttendees": []
}],
"bookingLimit": null
},
"success": true,
"suppress": false,
"version": "2.3.293",
"message": null,
"result": null,
"errors": null,
"code": null,
"flags": 0,
"redirect": null
}
I want to extract:
"startDate": "2020-08-18T13:30:00Z"
from each key, value pair in any of the returned slots. However, I cant work it out.
Extracting the whole of this nested dictionary would also contain the same data, but would then involve more work to tidy it up after.
"startDate": {
"ms": 1597757400000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 14,
"days": 0
}
I've tried loads of dictionary.get and dictionary.items variations, but cant seem to get anywhere.
I tried something like
key = ('startDate')
availability = dictionary.get(key)
print(availability)
this just returns 'none', so think im way off
Any pointers?
Thanks in advance!
Thanks for the full data. It makes testing easier :)
I had to replace null -> None, true -> True, false -> False
slot = {
"data": {
"services": [{
"id": None,
"name": None,
"services": [{
"id": None,
"name": "Car Park",
"met": True,
"filterCount": 1,
"primary": True,
"options": [{
"id": "9",
"images": [],
"available": True,
"calendarId": "AAAA",
"templateId": "BBBB",
"capacity": 0,
"name": "Car Park Slot 3",
"sessionId": "CCCC",
"functions": None,
"startDate": "2020-08-18T13:30:00Z", # <--this is what I want to extract
................
print("Start Date:", slot['data']['services'][0]['services'][0]['options'][0]['startDate'])
Output
Start Date: 2020-08-18T13:30:00Z
{
"result": [
{
"id": "140964",
"label": " 3688-RELT-PRD-LOGIN",
"location": "St. Louis, MO",
"startdate": "September 1, 2019 00:00:00",
"enddate": "September 12, 2019 04:57:41",
"statushistory": [
{
"status": "DOWN",
"statustype": "Content error",
"starttime": "09-01-2019 00:00",
"endtime": "09-11-2019 23:57",
"duration": "950261"
}
]
},
{
"id": "142285",
"label": " 4316_Rebar Messaging_PROD",
"location": "Chicago, IL",
"startdate": "September 1, 2019 00:00:00",
"enddate": "September 12, 2019 04:57:41",
"statushistory": [
{
"status": "UP",
"statustype": "OK",
"starttime": "09-01-2019 00:00",
"endtime": "09-11-2019 23:57",
"duration": "950261"
}
]
},
{
"id": "153272",
"label": "10002-Self Service SQL Failover",
"location": "Miami, FL",
"startdate": "September 1, 2019 00:00:00",
"enddate": "September 12, 2019 04:57:41",
"statushistory": [
{
"status": "UP",
"statustype": "OK",
"starttime": "09-01-2019 00:00",
"endtime": "09-11-2019 23:57",
"duration": "950261"
}
]
},
{
"id": "156764",
"label": "10054-SMARTSUPPLY-PRD",
"location": "Bangalore, India",
"startdate": "September 1, 2019 00:00:00",
"enddate": "September 12, 2019 04:57:41",
"statushistory": [
{
"status": "UP",
"statustype": "OK",
"starttime": "09-01-2019 00:00",
"endtime": "09-11-2019 23:57",
"duration": "950261"
}
]
},
{
"id": "156764",
"label": "10054-SMARTSUPPLY-PRD",
"location": "Mumbai, India",
"startdate": "September 1, 2019 00:00:00",
"enddate": "September 12, 2019 04:57:41",
"statushistory": [
{
"status": "UP",
"statustype": "OK",
"starttime": "09-08-2019 10:35",
"endtime": "09-11-2019 23:57",
"duration": "307316"
},
{
"status": "DOWN",
"statustype": "Timeout warning",
"starttime": "09-08-2019 10:31",
"endtime": "09-08-2019 10:35",
"duration": "274"
},
{
"status": "UP",
"statustype": "OK",
"starttime": "09-01-2019 00:00",
"endtime": "09-08-2019 10:31",
"duration": "642670"
}
]
}
]
}
i have this above json file .
which holds multiple data set this is just an example with 5 .
i want to pull the status value from the above json .
We can usual do it by result['statushistory'][0]['status']
But it pulls only the 5 values . It is returning only the first value of
the last statushistory .
How can i write a code which returns all the value of statushistory ?
And also if the statushistory doesnt have any status how can i mange that in the code ?(i.e return status only if statushistory has status present in it)
Something like:
statushistory_list = [result["statushistory"] for result in json_data["result"]]
status_list = [
[item["status"] for item in statushistory if "status" in item]
for statushistory in statushistory_list
]
this will get you:
[['DOWN'], ['UP'], ['UP'], ['UP'], ['UP', 'DOWN', 'UP']]
If it's not what you are looking for then, please show an example of the output you would like.
I want to find and delete 'indicent' object in my json using sublime. here's the regex
\s*+,\s*(.)+"\s*indices+"\s*:\s*+(.)\s*\s*(.)+\s*(.)+\s*+]
but, it's ran out of stack space. i think that regex isn't effiecient.
json example :
"created": "Fri Nov 27 11:12:43 +0000 2015",
"text": "https://t.co/8r5dQ7zRYG #johnl3375 Kim Gi Jung",
"source": "NOMOR1",
"hashtags": [
{
"text": "johnl3375",
"indices": [
24,
34
]
}
],
"url": [
{
"url": "https://t.co/8r5dQ7zRYG",
"expanded_url": "https://play.google.com/store/apps/details?id=com.aturkeuangan.nomor1#refid=johnl3375",
"display_url": "play.google.com/store/apps/det…",
"indices": [
0,
23
]
}
]
i want json like this
"created": "Fri Nov 27 11:12:43 +0000 2015",
"text": "https://t.co/8r5dQ7zRYG #johnl3375 Kim Gi Jung",
"source": "NOMOR1",
"hashtags": [
{
"text": "johnl3375"
}
],
"url": [
{
"url": "https://t.co/8r5dQ7zRYG",
"expanded_url": "https://play.google.com/store/apps/details?id=com.aturkeuangan.nomor1#refid=johnl3375",
"display_url": "play.google.com/store/apps/det…"
}
]
what should my regex be?
This works for me in ST3 using your JSON example: [\s,]+"indices":[^]]+]
I have employers array as below; how to get employers:id and featuredReview:id using JSON expression.
"employers": [
{
"id": 194,
"name": "Target",
"website": "www.target.com",
"isEEP": false,
"exactMatch": false,
"industry": "Department, Clothing, & Shoe Stores",
"numberOfRatings": 11531,
"squareLogo": "http://media.glassdoor.com/sqll/194/target-squarelogo.png",
"overallRating": 3.2,
"ratingDescription": "OK",
"cultureAndValuesRating": "3.3",
"seniorLeadershipRating": "2.8",
"compensationAndBenefitsRating": "3.0",
"careerOpportunitiesRating": "3.0",
"workLifeBalanceRating": "3.0",
"recommendToFriendRating": "0.6",
"featuredReview": {
"id": 6613365,
"currentJob": false,
"reviewDateTime": "2015-05-15 16:32:06.997",
"jobTitle": "Executive Team Leader",
"location": "Buena Park, CA",
"jobTitleFromDb": "Executive Team Leader",
"headline": "Unrealistic expectations for leadership",
"overall": 4,
"overallNumeric": 4
},
"ceo": {
"name": "Brian Cornell",
"title": "CEO",
"numberOfRatings": 1127,
"pctApprove": 66,
"pctDisapprove": 34
}
}]
employers[0].id
employers[0].featuredReview.id