How to select some properties from a json result - javascript

I am trying to build a simple react app which lists my philips hue bulb name and state(on or off). I have API call which results in the following json. Not sure how to pull bulb name and state.on status.
Here is my json result which gets the list of bulbs connected to my hue bridge. I get this result when i fetch via a the philips hue API.
{
"1": {
"state": {
"on": false,
"bri": 254,
"hue": 50116,
"sat": 248,
"effect": "none",
"xy": [
0.2444,
0.0969
],
"ct": 500,
"alert": "select",
"colormode": "xy",
"mode": "homeautomation",
"reachable": true
},
"swupdate": {
"state": "noupdates",
"lastinstall": "2021-08-19T18:10:44"
},
"type": "Extended color light",
"name": "TV 2",
"modelid": "LCT016",
"manufacturername": "Signify Netherlands B.V.",
"productname": "Hue color lamp",
"capabilities": {
"certified": true,
"control": {
"mindimlevel": 1000,
"maxlumen": 800,
"colorgamuttype": "C",
"colorgamut": [
[
0.6915,
0.3083
],
[
0.1700,
0.7000
],
[
0.1532,
0.0475
]
],
"ct": {
"min": 153,
"max": 500
}
},
"streaming": {
"renderer": true,
"proxy": true
}
},
"config": {
"archetype": "sultanbulb",
"function": "mixed",
"direction": "omnidirectional",
"startup": {
"mode": "safety",
"configured": true
}
},
"uniqueid": "00:17:88:01:03:db:75:df-0b",
"swversion": "1.88.1",
"swconfigid": "47ACF9B2",
"productid": "Philips-LCT016-1-A19ECLv5"
},
"2": {
"state": {
"on": false,
"bri": 254,
"hue": 8417,
"sat": 140,
"effect": "none",
"xy": [
0.4573,
0.4100
],
"ct": 366,
"alert": "select",
"colormode": "ct",
"mode": "homeautomation",
"reachable": true
},
"swupdate": {
"state": "noupdates",
"lastinstall": "2021-08-19T18:10:39"
},
"type": "Extended color light",
"name": "Study",
"modelid": "LCT016",
"manufacturername": "Signify Netherlands B.V.",
"productname": "Hue color lamp",
"capabilities": {
"certified": true,
"control": {
"mindimlevel": 1000,
"maxlumen": 800,
"colorgamuttype": "C",
"colorgamut": [
[
0.6915,
0.3083
],
[
0.1700,
0.7000
],
[
0.1532,
0.0475
]
],
"ct": {
"min": 153,
"max": 500
}
},
"streaming": {
"renderer": true,
"proxy": true
}
},
"config": {
"archetype": "sultanbulb",
"function": "mixed",
"direction": "omnidirectional",
"startup": {
"mode": "safety",
"configured": true
}
},
"uniqueid": "00:17:88:01:03:94:fa:07-0b",
"swversion": "1.88.1",
"swconfigid": "47ACF9B2",
"productid": "Philips-LCT016-1-A19ECLv5"
}
}

You can map them into an array using map(). Since map only works on arrays, and your data is an object, you can use Object.values to return an array of the object's values and use map on that, like this:
const data={1:{state:{on:!1,bri:254,hue:50116,sat:248,effect:"none",xy:[.2444,.0969],ct:500,alert:"select",colormode:"xy",mode:"homeautomation",reachable:!0},swupdate:{state:"noupdates",lastinstall:"2021-08-19T18:10:44"},type:"Extended color light",name:"TV 2",modelid:"LCT016",manufacturername:"Signify Netherlands B.V.",productname:"Hue color lamp",capabilities:{certified:!0,control:{mindimlevel:1e3,maxlumen:800,colorgamuttype:"C",colorgamut:[[.6915,.3083],[.17,.7],[.1532,.0475]],ct:{min:153,max:500}},streaming:{renderer:!0,proxy:!0}},config:{archetype:"sultanbulb",function:"mixed",direction:"omnidirectional",startup:{mode:"safety",configured:!0}},uniqueid:"00:17:88:01:03:db:75:df-0b",swversion:"1.88.1",swconfigid:"47ACF9B2",productid:"Philips-LCT016-1-A19ECLv5"},2:{state:{on:!1,bri:254,hue:8417,sat:140,effect:"none",xy:[.4573,.41],ct:366,alert:"select",colormode:"ct",mode:"homeautomation",reachable:!0},swupdate:{state:"noupdates",lastinstall:"2021-08-19T18:10:39"},type:"Extended color light",name:"Study",modelid:"LCT016",manufacturername:"Signify Netherlands B.V.",productname:"Hue color lamp",capabilities:{certified:!0,control:{mindimlevel:1e3,maxlumen:800,colorgamuttype:"C",colorgamut:[[.6915,.3083],[.17,.7],[.1532,.0475]],ct:{min:153,max:500}},streaming:{renderer:!0,proxy:!0}},config:{archetype:"sultanbulb",function:"mixed",direction:"omnidirectional",startup:{mode:"safety",configured:!0}},uniqueid:"00:17:88:01:03:94:fa:07-0b",swversion:"1.88.1",swconfigid:"47ACF9B2",productid:"Philips-LCT016-1-A19ECLv5"}};
let bulbs = Object.values(data).map(
m=>{return {name: m.name, state: m.state.on}}
);
console.log(bulbs);

Related

Is there a way in Vega lite to use different color encodings on a choropleth map, the map has a drop down menu

As stated the map has a drop down menu that changes the display of the map, it selects different columns in the dataset. Ideally I would like to show a different "scheme" for input one and input two or what would also work in my case is to use "reverse" the "scale" encoding to reverse the color scheme for one of the two data columns being loaded
Code extract:
{"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"config": {
"background":"white",
"view": {"stroke": "trasparent"}},
"width": 700,
"height": 500,
"data": {
"url": "https://unpkg.com/world-atlas#1.1.4/world/110m.json",
"format": {
"type": "topojson",
"feature": "countries"}
},
"projection": {
"type": "naturalEarth2"},
"mark": {
"type": "geoshape",
"stroke": "rgb(50, 50, 50)",
"strokeWidth":0.3},
"transform": [
{"calculate":"parseInt(datum.id)", "as":"id_N"},
{
"lookup": "id_N",
"from": {
"key": "id",
"fields": ["alpha3", "name"],
"data": {"url": "data1"}}
},
{"lookup": "alpha3",
"from":{
"data":{
"url":"data2"},
"key": "ISO3",
"fields":["Vulnerability", "Gain"]
}
},
{"calculate": "datum.Vulnerability", "as": "Climate Vulnerability"},
{"calculate": "datum.Gain", "as": "Overall Vulnerability Index"},
{"calculate": "datum[Select]","as": "varSelected"},
],
"params": [
{"name": "Select",
"value": "Vulnerability",
"bind": {
"input": "select",
"options": [
"Climate Vulnerability",
"Overall Vulnerability Index"]}}],
"encoding": {
"color":{
"field":"varSelected",
"type":"quantitative",
"title": null,
"scale":{
"scheme": {"name": "turbo", "count":5}
}
},
"tooltip":[
{"field":"name", "title":"Country"},
{"field":"varSelected","title":"Score","type":"quantitative"}],
}

prepare dataset from json to train RNN in brain.js and node

I have two separate json files that are the response provided from an online api service and will hold the informations about the last two football season of Italian Serie A.
I want to use the unique team id and the result of the match to create a dataset to use with brain.js, what's the best way to achive this?
I've tried to unify the files by copying the content of the second file into the first ove but I will then have two matches array and other duplied fields and I'm not sure on how to process data to ingest into brain.js
{
"filters": {
"season": 2021
},
"resultSet": {
"count": 380,
"first": "2021-08-21",
"last": "2022-05-22",
"played": 380
},
"competition": {
"id": 2019,
"name": "Serie A",
"code": "SA",
"type": "LEAGUE",
"emblem": "https://crests.football-data.org/SA.png"
},
"matches": [
{
"area": {
"id": 2114,
"name": "Italy",
"code": "ITA",
"flag": "https://crests.football-data.org/784.svg"
},
"competition": {
"id": 2019,
"name": "Serie A",
"code": "SA",
"type": "LEAGUE",
"emblem": "https://crests.football-data.org/SA.png"
},
"season": {
"id": 757,
"startDate": "2021-08-21",
"endDate": "2022-05-22",
"currentMatchday": 38,
"winner": null
},
"id": 333779,
"utcDate": "2021-08-21T16:30:00Z",
"status": "FINISHED",
"matchday": 1,
"stage": "REGULAR_SEASON",
"group": null,
"lastUpdated": "2022-06-25T08:20:15Z",
"homeTeam": {
"id": 108,
"name": "FC Internazionale Milano",
"shortName": "Inter",
"tla": "INT",
"crest": "https://crests.football-data.org/108.png"
},
"awayTeam": {
"id": 107,
"name": "Genoa CFC",
"shortName": "Genoa",
"tla": "GEN",
"crest": "https://crests.football-data.org/107.svg"
},
"score": {
"winner": "HOME_TEAM",
"duration": "REGULAR",
"fullTime": {
"home": 4,
"away": 0
},
"halfTime": {
"home": 2,
"away": 0
}
},
"odds": {
"msg": "Activate Odds-Package in User-Panel to retrieve odds."
},
"referees": [
{
"id": 11336,
"name": "Valerio Marini",
"type": "REFEREE",
"nationality": "Italy"
}
]
},{ ... } //
],
// here I will have the other season
"filters": {
"season": 2020
},
"resultSet": {
"count": 380,
"first": "2021-08-21",
"last": "2022-05-22",
"played": 380
},
"competition": {
"id": 2019,
"name": "Serie A",
"code": "SA",
"type": "LEAGUE",
"emblem": "https://crests.football-data.org/SA.png"
},
"matches": [
{...}]
}
At the momen I've used this code on the json I have created to have training data.
const dataset = Object.values(samples.matches).map( (match) => {
let result
switch( match.score.winner ) {
case 'HOME_TEAM':
result = 0
break;
case 'AWAY_TEAM':
result = 1
break;
case 'DRAW':
result = 2
break;
}
return {
homeTeam: match.homeTeam.id,
awayTeam: match.awayTeam.id,
matchResult: result
}
})
//console.log( dataset )
const trainingData = dataset.map( (data) => {
return {
input: [ data.homeTeam, data.awayTeam ],
output: [ data.matchResult ]
}
})
this is what the data I'm using with brain will look
{ homeTeam: 112, awayTeam: 1106, matchResult: 2 },
{ homeTeam: 472, awayTeam: 113, matchResult: 1 },
{ homeTeam: 584, awayTeam: 98, matchResult: 1 },
{ homeTeam: 99, awayTeam: 107, matchResult: 2 },
{ homeTeam: 471, awayTeam: 1106, matchResult: 0 },
{ homeTeam: 472, awayTeam: 488, matchResult: 0 },
where 0 is when home team win, 1 when away team win and 2 if draw, but I need to have a better solution for handle this case.

Need to get Name, Node Name and Phase Values from API

I am trying to get Name, Node Name and Phase values from JSON Data using JavaScript. Here is my JavaScript
<script>
$(document).ready(function () {
$.getJSON('http://ec2-3-82-117-70.compute-1.amazonaws.com:8080/api/v0/retrievePodStatus/default',
function (data) {
console.log(data)
document.body.append("Name: " + data.items[1].metadata.name);
// document.body.append(data.items[1].metadata.name);
// document.body.append(data.items[0].spec.nodeName);
});
});
</script>
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
"apiVersion": "v1",
"items": [
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}
],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [
{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}
],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
},
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
Thanks, Much Appreciated
You were close with the code you posted. You just needed items[0] instead of items[1]. Remember the first element of an array is always 0. Other than that its as easy as checking the open and close brackets [] or {} to see where each nested object/array starts and ends.
Code:
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
snippet:
var data = {
"apiVersion": "v1",
"items": [{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}]
}],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}]
},
"status": {
"conditions": [{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
}],
}
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
console.log(name)
console.log(nodeName)
console.log(phase)

Strange values with bar stack Open Flash Chart

I'm trying to use the bar stack graph with Open Flash Chart. The JSON object I generate is containing correct values and when the chart is loaded the first part of the bar stack is correct but the ones after have gotten way of values.
The JSON object:
{
"title": {
"text": "Aktiviteter",
"style": "{font-size: 15px; text-align: center;}"
},
"elements": [
{
"type": "bar_stack",
"colours": [
"#b727e3",
"#f55225",
"#16196e",
"#b3ac3",
"#f01673"
],
"keys": [
{
"colour": "#b727e3",
"text": "Utst\u00e4llningar",
"font-size": 13
},
{
"colour": "#f55225",
"text": "Kurser",
"font-size": 13
},
{
"colour": "#16196e",
"text": "Resor",
"font-size": 13
},
{
"colour": "#b3ac3",
"text": "Kulturarrangemang",
"font-size": 13
},
{
"colour": "#f01673",
"text": "F\u00f6rel\u00e4sningar",
"font-size": 13
}
],
"values": [
[
{
"val": "205",
"tip": "Utst\u00e4llningar 2013<br>Antal #val#"
},
{
"val": "52",
"tip": "Kurser 2013<br>Antal #val#"
},
{
"val": "161",
"tip": "Resor 2013<br>Antal #val#"
},
{
"val": "123",
"tip": "Kulturarrangemang 2013<br>Antal #val#"
},
{
"val": "123",
"tip": "F\u00f6rel\u00e4sningar 2013<br>Antal #val#"
}
]
],
"on-show": {
"type": "pop",
"cascade": 1,
"delay": 0.5
}
}
],
"x_axis": {
"labels": {
"rotate": 20,
"labels": [
"2013"
]
}
},
"y_axis": {
"min": 0,
"steps": 66,
"max": 830
},
"tooltip": {
"mouse": 2
},
"bg_colour": "#FFFFFF"
}
Item #2:
{
"val": "52",
"tip": "Kurser 2013<br>Antal #val#"
},
, when displayed, got a value of 20 347 instead of 52 and therefore doesnt fit into the y-axis. (image http://s8.postimg.org/jfeh9u2d1/Namnlo_st.png)
I load the Chart by
<script type="text/javascript" src="js/js/swfobject.js"></script>
<script type="text/javascript">
swfobject.embedSWF(
"open-flash-chart.swf", "my_chart", "550", "200",
"9.0.0", "expressInstall.swf",
{"data-file":"get_stats2.php?action=activities%26type=total%26limit=1"}
);
Any suggestions?

JSON Jquery Array Trouble

How do I get to, Value, Editions, Price, Average?
My non working code:
.append(th.clone().text(value.editions[0].price[1].average))
The JSON layout:
{
"name": "About Face",
"id": "about-face",
"url": "https://api.deckbrew.com/mtg/cards/about-face",
"store_url": "http://store.tcgplayer.com/magic/urzas-legacy/about-face",
"types": [
"instant"
],
"colors": [
"red"
],
"cmc": 1,
"cost": "{R}",
"text": "Switch target creature's power and toughness until end of turn.",
"formats": {
"commander": "legal",
"legacy": "legal",
"vintage": "legal"
},
"editions": [
{
"set": "Urza's Legacy",
"price": {
"low": 89,
"average": 154,
"high": 198
},
"url": "https://api.deckbrew.com/mtg/cards?multiverseid=12414",
}
]
}
My Fiddle can be found here:
http://jsfiddle.net/w2QHz/13/
You should use
.append(th.clone().text(value.editions[0].price.average))
Remove [0] from price, since price is an object not an array.

Categories

Resources