Need help cleaning up iterating through nested JSON - python-3.x

I'm iterating through JSON content. I'm returning the sensor name + the temperature. There are two value keys under capability. I'm having trouble coming up with the simple logic to ignore the second one. I'm fairly new to python but feel like this is a simple adjustment. I just can't seem to find a good example on how to ignore the second value its pulling.
DATA:
"remoteSensors": [
{
"id": "rs:100",
"name": "Guest Bedroom",
"type": "ecobee3_remote_sensor",
"code": "TPCM",
"inUse": false,
"capability": [
{
"id": "1",
"type": "temperature",
"value": "690"
},
{
"id": "2",
"type": "occupancy",
"value": "false"
}
]
},
{
"id": "rs:101",
"name": "Mudd Room",
"type": "ecobee3_remote_sensor",
"code": "X9YF",
"inUse": false,
"capability": [
{
"id": "1",
"type": "temperature",
"value": "572"
},
{
"id": "2",
"type": "occupancy",
"value": "false"
}
]
},
{
"id": "rs:102",
"name": "Master Bedroom",
"type": "ecobee3_remote_sensor",
"code": "YDNZ",
"inUse": false,
"capability": [
{
"id": "1",
"type": "temperature",
"value": "694"
},
{
"id": "2",
"type": "occupancy",
"value": "true"
}
]
},
{
"id": "ei:0",
"name": "Main Floor",
"type": "thermostat",
"inUse": true,
"capability": [
{
"id": "1",
"type": "temperature",
"value": "725"
},
{
"id": "2",
"type": "humidity",
"value": "37"
},
{
"id": "3",
"type": "occupancy",
"value": "false"
}
]
}
]
CODE:
import requests
import json
url = 'https://api.ecobee.com/1/thermostat'
header = {'Content-Type': 'application/json;charset=UTF-8',
'Authorization': 'Bearer ZkEf7ONibogGpMQibem3SlhXhEOS99zK'}
params = {'json': ('{"selection":{"selectionType":"registered",'
'"includeRuntime":"true",'
'"includeSensors":"true",'
'"includeProgram":"true",'
'"includeEquipmentStatus":"true",'
'"includeEvents":"true",'
'"includeWeather":"true",'
'"includeSettings":"true"}}')}
request = requests.get(url, headers=header, params=params)
#print(request)
thermostats = request.json()['thermostatList']
remote_sensors = thermostats[0]['remoteSensors']
for eachsensor in thermostats[0]['remoteSensors']:
for temp in eachsensor['capability']:
name = eachsensor.get('name')
temp = temp.get('value')
print(name, temp)
Actual Results:
Guest Bedroom 690
Guest Bedroom false
Mudd Room 579
Mudd Room false
Master Bedroom 698
Master Bedroom false
Main Floor 731
Main Floor false
Expected Results:
Guest Bedroom 690
Mudd Room 579
Master Bedroom 698
Main Floor 731
Thanks for the help! #Naveen
Fixed:
for eachsensor in thermostats[0]['remoteSensors']:
for temp in eachsensor['capability']:
name = eachsensor.get('name')
tempr = temp.get('value')
id = temp.get('id')
if id == '1':
print(name, tempr, id)

Related

Received an invalid_authentication error when querying a Foursquare venue

I am trying to query for details of venues using the Foursquare venues
API, but i received a "invalid_auth" error
VENUE_ID='54ea41ad498e9a11e9e13308'
VERSION = '20190823'
venueurl = 'https://api.foursquare.com/v2/venues/{}&client_id={}&client_secret={}&v={}'.format(VENUE_ID, CLIENT_ID, CLIENT_SECRET, VERSION)
venueresults = requests.get(venueurl).json()
venueresults
This is the error i received.
{'meta': {'code': 400, 'errorType': 'invalid_auth', 'errorDetail':
'Missing access credentials. See
https://developer.foursquare.com/docs/api/configuration/authentication
for details.', 'requestId': '5d613b698afbe000358acf53'},
'response': {}}
I expect to receive a response as shown below (shortened as the
response is too long.
https://foursquare.com/developers/explore#req=venues%2F54ea41ad498e9a11e9e13308
{ "meta": { "code": 200 "requestId": "5d613941075a420023f41750" }
"notifications": [ { "type": "notificationTray" "item": {
"unreadCount": 0 } } ] "response": { "venue": { "id":
"54ea41ad498e9a11e9e13308" "name": "Roselle Desserts" "contact": {
"phone": "+14163688188" "formattedPhone": "+1 416-368-8188" "twitter":
"roselle_to" } "location": { "address": "362 King St E" "crossStreet":
"Trinity St" "lat": 43.653446723052674 "lng": -79.3620167174383
"labeledLatLngs": [ { "label": "display" "lat": 43.653446723052674
"lng": -79.3620167174383 } ] "postalCode": "M5A 1K9" "cc": "CA"
"city": "Toronto" "state": "ON" "country": "Canada"
"formattedAddress": [ "362 King St E (Trinity St)" "Toronto ON M5A
1K9" "Canada" ] } "canonicalUrl":
"https://foursquare.com/v/roselle-desserts/54ea41ad498e9a11e9e13308"
"categories": [ { "id": "4bf58dd8d48988d16a941735" "name": "Bakery"
"pluralName": "Bakeries" "shortName": "Bakery" "icon": { "prefix":
"https://ss3.4sqi.net/img/categories_v2/food/bakery_" "suffix": ".png"
} "primary": true } { "id": "4bf58dd8d48988d1d0941735" "name":
"Dessert Shop" "pluralName": "Dessert Shops" "shortName": "Desserts"
"icon": { "prefix":
"https://ss3.4sqi.net/img/categories_v2/food/dessert_" "suffix":
".png" } } { "id": "4bf58dd8d48988d1c9941735" "name": "Ice Cream Shop"
"pluralName": "Ice Cream Shops" "shortName": "Ice Cream" "icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/food/icecream_"
"suffix": ".png" } } ] "verified": false "stats": { "tipCount": 15
"usersCount": 674 "checkinsCount": 561 "visitsCount": 1203 } "url":
"http://www.roselleto.com" "price": { "tier": 1 "message": "Cheap"
"currency": "$" } "likes": { "count": 45 "groups": [ { "type":
"others" "count": 45 "items": [ ] } ] "summary": "45 Likes" } "like":
false "dislike": false "ok": false "rating": 8.8 "ratingColor":
"73CF42" "ratingSignals": 54 "allowMenuUrlEdit": true "beenHere": {
"count": 0 "unconfirmedCount": 0 "marked": false
"lastCheckinExpiredAt": 0 } "specials": { "count": 0 "items": [ ] }
"photos": { "count": 39 "groups": [ { "type": "checkin" "name":
"Friends' check-in photos" "count": 0 "items": [ ] } { "type": "venue"
"name": "Venue photos" "count": 39 "items": [ "0": { "id":
"5d59a14744209c00089c596b" "createdAt": 1566155079 "source": { "name":
"Swarm for iOS" "url": "https://www.swarmapp.com"
etc
I have found the answer, a "?" instead of "&" is required after the venue_id
'https://api.foursquare.com/v2/venues/{}?client_id={}&client_secret={}&v={}'.format(VENUE_ID, CLIENT_ID, CLIENT_SECRET, VERSION)
Refer to the Q&A below:
Authentication error in nested API request

How to fix "it doesn't support that" when I query Alexa retrievable property

I have this endpoint with powerState and connectivity properties both retrievable:
{
"endpointId": "123",
"manufacturerName": "abc",
"friendlyName": "lamp",
"description": "lamp",
"displayCategories": [
"LIGHT"
],
"capabilities": [
{
"type": "AlexaInterface",
"interface": "Alexa.PowerController",
"version": "3",
"properties": {
"supported": [{
"name": "powerState"
}],
"retrievable": true
}
},
{
"type": "AlexaInterface",
"interface": "Alexa.EndpointHealth",
"version": "3",
"properties": {
"supported": [{
"name": "connectivity"
}],
"retrievable": true
}
}
],
"cookie": {}
}
I respond to ReportState request by sending the state of both properties:
{
"context": {
"properties": [
{
"namespace": "Alexa.PowerController",
"name": "powerState",
"value": "ON",
"timeOfSample": "2019-01-10T10:17:19.99Z",
"uncertaintyInMilliseconds": 50
},
{
"namespace": "Alexa.EndpointHealth",
"name": "connectivity",
"value": {
"value": "OK"
},
"timeOfSample": "2019-01-10T10:17:19.90Z",
"uncertaintyInMilliseconds": 50
}
]
},
"event": {
"header": {
"namespace": "Alexa",
"name": "StateReport",
"payloadVersion": "3",
"messageId": "cde",
"correlationToken": "efg123"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "ab123"
},
"endpointId": "123",
"cookie": {}
},
"payload": {}
}
}
And I send the same context in the PowerController response.
In the Alexa app I can see my device, turn it on and off and view its state rightly. I can ask Alexa to turn on and off my device and the response in "OK", but if I try to ask:** "Is my device turned on?" ** Alexa answers that this device doesn't support that.
The skill language is Italian and PowerController documentation https://developer.amazon.com/it/docs/device-apis/alexa-powercontroller.html says that query is supported.
What am I missing?

Jira Python Keyerror on issue links

I have a script which goes to fetch info via Jira API then its doing some comparison but i'm getting the following error :
Error :
"errorMessage": "'outwardIssue'"
"errorType": "KeyError"
JSON format:
"issuelinks": [
{
"id": "1255",
"self": "https://jiraurl/rest/api/2/issueLink/0000",
"type": {
"id": "10030",
"name": "Arises ",
"inward": "gives rise to",
"outward": "arises from",
"self": "https://jiraurl/rest/api/2/issueLinkType/0000"
},
"outwardIssue": {
"id": "1251575",
"key": "temp-511",
"self": "https://jiraurl/rest/api/2/issue/0000",
"fields": {
"summary": "a summary",
"status": {
"self": "https://jiraurl/rest/api/2/status/6",
"description": "test",
"iconUrl": "",
"name": "Closed",
"id": "6",
"statusCategory": {
"self": "https://jiraurl/rest/api/2/statuscategory/3",
"id": 3,
"key": "done",
"colorName": "green",
"name": "Done"
}
},
"issuetype": {
"self": "https://jiraurl/rest/api/2/issuetype/20",
"id": "20",
"description": "Problem ",
"iconUrl": "https://jiraurl/images/icons/issuetypes/documentation.png",
"name": "Problem",
"subtask": false
}
}
}
}
]
Python Statement where we believe the issue is:
if (problem['fields']['issuelinks'][0]['outwardIssue']) and (problem['fields']['issuelinks'][0]['type']['outward'] == "arises from"):
isitanissue = False
I cant see why its stuck on'outwardIssue' ?
try this:
issue = jira.issue("XX)
if (issue.raw['fields']['issuelinks'][0]['outwardIssue']) and (issue.raw['fields']['issuelinks'][0]['type']['outward'] == "arises from"): isitanissue = False

Adaptive Cards doesn't work in MBF's Emulator running in Ubuntu 16.04

I am trying to implement AdaptiveCard into one of my dialogs using node.js. However once I run the emulator I get the following message instead of rendered AdaptiveCard:
[File of type 'application/vnd.microsoft.card.adaptive'].
Can anyone tell me what can be the problem?
I am running on Ubuntu 16.04, MBF Emulator v.3.5.31-alpha, microsoft-adaptivecards v.0.6.1.
Here is code from inside of one of my dialogs:
var msg = new builder.Message(session)
.addAttachment({
contentType: "application/vnd.microsoft.card.adaptive",
content: {
type: "AdaptiveCard",
body: [
{
"type": "TextBlock",
"text": msg_text,
},
{
"type": "Input.ChoiceSet",
"id": "myColor4",
"isMultiSelect": true,
"value": "1",
"style": "expanded",
"choices": [
{
"title": "Red",
"value": "1",
"isSelected": true
},
{
"title": "Green",
"value": "2"
},
{
"title": "Blue",
"value": "3",
"isSelected": true
}
]
}
],
"actions": [
{
"type": "Action.Submit",
"title": "Sent",
"data": {
"myProperty": 12
}
}
],
}
});
session.send(msg);
This is detailed response, it contains all elements of the AdaptiveCard that I declared(but still it does not render):
{
"type": "message",
"attachments": [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"type": "AdaptiveCard",
"body": [
{
"type": "TextBlock",
"text": "What color do you want?"
},
{
"type": "Input.ChoiceSet",
"id": "myColor4",
"isMultiSelect": true,
"value": "1",
"style": "expanded",
"choices": [
{
"title": "Red",
"value": "1",
"isSelected": true
},
{
"title": "Green",
"value": "2"
},
{
"title": "Blue",
"value": "3",
"isSelected": true
}
]
}
],
"actions": [
{
"type": "Action.Submit",
"title": "Sent",
"data": {
"myProperty": 12
}
}
]
}
}
],
"locale": "en-US",
"localTimestamp": "2017-09-17T19:21:17+02:00",
"from": {
"id": "default-bot",
"name": "Bot"
},
"recipient": {
"id": "default-user"
},
"inputHint": "acceptingInput",
"id": "heam84b9dn5b",
"replyToId": "71j1d6mbmk3l",
"channelId": "emulator",
"timestamp": "2017-09-17T17:21:17.379Z",
"conversation": {
"id": "fdikc23llm5"
}
}

JSON payload for Adaptive cards gets jumbled in body of http request

While trying to get the JSON from the body of a request, JSON.Parse jumbles the JSON elements, hence the webchat does not recognize it as an adaptive card.. Please help..
Node.JS Code:
var msgContent = {};
msgContent = getjson(function(resb){});
var msg = new builder.Message(session)
.addAttachment(msgContent);
session.endDialog(msg);
function getjson(callback){
request.JSON = true;
request.post("https://someapi.web.net",
function (error, response, body){
var resb = {};
resb = JSON.parse(body);
console.log(resb);
callback(resb);
});
};
Intended JSON:
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"type": "AdaptiveCard",
"body": [{
"type": "ColumnSet",
"columns": [{
"type": "Column",
"size": 2,
"items": [{
"type": "TextBlock",
"text": "Tell us about yourself...",
"weight": "bolder",
"size": "large"
},
{
"type": "TextBlock",
"text": "We just need a few more details to get you booked for the trip of a lifetime!",
"isSubtle": true,
"wrap": true
},
{
"type": "TextBlock",
"text": "Don't worry, we'll never share or sell your information.",
"isSubtle": true,
"wrap": true,
"size": "small"
},
{
"type": "TextBlock",
"text": "Your name",
"wrap": true
},
{
"type": "Input.Text",
"id": "myName",
"placeholder": "Last, First"
},
{
"type": "TextBlock",
"text": "Your email",
"wrap": true
},
{
"type": "Input.Text",
"id": "myEmail",
"placeholder": "youremail#example.com",
"style": "email"
},
{
"type": "TextBlock",
"text": "Phone Number"
},
{
"type": "Input.Text",
"id": "myTel",
"placeholder": "xxx.xxx.xxxx",
"style": "tel"
}
]
},
{
"type": "Column",
"size": 1,
"items": [{
"type": "Image",
"url": "https://upload.wikimedia.org/wikipedia/commons/b/b2/Diver_Silhouette%2C_Great_Barrier_Reef.jpg",
"size": "auto"
}]
}
]
}],
"actions": [{
"type": "Action.Submit",
"title": "Submit"
}]
}
Received JSON:
{'$schema': 'http://adaptivecards.io/schemas/adaptive-card.json',
content:
{ actions: [ [Object] ],
body: [ [Object] ],
type: 'AdaptiveCard' },
contentType: 'application/vnd.microsoft.card.adaptive' }
JSON objects are technically objects with unordered properties, so what you're seeing is a feature, not a bug.
See https://stackoverflow.com/a/5525820/5199616 for detailed discussion.

Resources