I have this JSON:
{"id":"162","name":"Xiaomi Temperature Humidity Sensor","label":"Fridge Temperature","attributes":[{"name":"battery","currentValue":23,"dataType":"NUMBER"},{"name":"batteryLastReplaced","currentValue":"Jun 19 2019","dataType":"STRING"},{"name":"humidity","currentValue":39.2,"dataType":"NUMBER"},{"name":"lastCheckinEpoch","currentValue":null,"dataType":"STRING"},{"name":"lastCheckinTime","currentValue":null,"dataType":"DATE"},{"name":"pressure","currentValue":100.14,"dataType":"NUMBER"},{"name":"temperature","currentValue":3.02,"dataType":"NUMBER"}],"capabilities":["TemperatureMeasurement",{"attributes":[{"name":"temperature","dataType":null}]},"RelativeHumidityMeasurement",{"attributes":[{"name":"humidity","dataType":null}]},"Battery",{"attributes":[{"name":"battery","dataType":null}]},"Sensor","PressureMeasurement",{"attributes":[{"name":"pressure","dataType":null}]}],"commands":["resetBatteryReplacedDate"]}
I'm trying to extract the temperature (3.02), pressure (100.14) and humidity (39.2). Because it's nested (if I understand correctly?) I'm trying some recursive code I found. But I'm really lost to understand how to extract the data I need.
Here is what I have so far:
function updateTPH(deviceId, index, array) {
var responseString = '';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
responseString = xhttp.responseText;
alert(responseString);
var element = document.getElementById(deviceId);
// Converting JSON object to JS object
var obj = JSON.parse(json);
// Define recursive function to print nested values
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
document.write(obj[k] + "<br>");
};
}
};
// Printing all the values from the resulting object
printValues(obj);
}
};
xhttp.open("GET", "http://192.168.0.167/apps/api/" + myMakerAPI + "/devices/" + deviceId + "?access_token=" + myAccessToken, true);
xhttp.send();
};
I'm getting the parameters printed to the page ok, but I cant work out how to isolate the parameters I want into variables I can then use. Any assistance would be much appreciated!
Yes the values are "nested". If you want to access humidity for example you would do something like this: obj["attributes"][2]["currentValue"], because the humidity value is inside the third element of "attributes".
Humidity:
obj["attributes"][2]["currentValue"];
Pressure:
obj["attributes"][5]["currentValue"];
Temperature:
obj["attributes"][6]["currentValue"];
You can assign those values to a variable like so:
var temperature = obj["attributes"][6]["currentValue"];
You can access the inner attributes with the index like below
myObj["attributes"][2]["currentValue"];
Otherwise, you can use below code to generate a JSON object like below and use myObj["temperature"]
{
"battery": 23,
"batteryLastReplaced": "Jun 19 2019",
"humidity": 39.2,
"lastCheckinEpoch": null,
"lastCheckinTime": null,
"pressure": 100.14,
"temperature": 3.02
}
let myJSON = {"id":"162","name":"Xiaomi Temperature Humidity Sensor","label":"Fridge Temperature","attributes":[{"name":"battery","currentValue":23,"dataType":"NUMBER"},{"name":"batteryLastReplaced","currentValue":"Jun 19 2019","dataType":"STRING"},{"name":"humidity","currentValue":39.2,"dataType":"NUMBER"},{"name":"lastCheckinEpoch","currentValue":null,"dataType":"STRING"},{"name":"lastCheckinTime","currentValue":null,"dataType":"DATE"},{"name":"pressure","currentValue":100.14,"dataType":"NUMBER"},{"name":"temperature","currentValue":3.02,"dataType":"NUMBER"}],"capabilities":["TemperatureMeasurement",{"attributes":[{"name":"temperature","dataType":null}]},"RelativeHumidityMeasurement",{"attributes":[{"name":"humidity","dataType":null}]},"Battery",{"attributes":[{"name":"battery","dataType":null}]},"Sensor","PressureMeasurement",{"attributes":[{"name":"pressure","dataType":null}]}],"commands":["resetBatteryReplacedDate"]}; let myAttributes = myJSON.attributes.reduce((object, item) => { object[item.name] = item.currentValue; return object; }, {}); console.log(myAttributes); console.log(myAttributes.temperature);
There no need for recursive calls. Your datatype is already predefined, so you can just loop through it.
const obj = { id: "162", name: "Xiaomi Temperature Humidity Sensor", label: "Fridge Temperature", attributes: [ { name: "battery", currentValue: 23, dataType: "NUMBER" }, { name: "batteryLastReplaced", currentValue: "Jun 19 2019", dataType: "STRING", }, { name: "humidity", currentValue: 39.2, dataType: "NUMBER" }, { name: "lastCheckinEpoch", currentValue: null, dataType: "STRING" }, { name: "lastCheckinTime", currentValue: null, dataType: "DATE" }, { name: "pressure", currentValue: 100.14, dataType: "NUMBER" }, { name: "temperature", currentValue: 3.02, dataType: "NUMBER" }, ], capabilities: [ "TemperatureMeasurement", { attributes: [{ name: "temperature", dataType: null }] }, "RelativeHumidityMeasurement", { attributes: [{ name: "humidity", dataType: null }] }, "Battery", { attributes: [{ name: "battery", dataType: null }] }, "Sensor", "PressureMeasurement", { attributes: [{ name: "pressure", dataType: null }] }, ], commands: ["resetBatteryReplacedDate"], }; function printValues(obj) { const { attributes } = obj; attributes.forEach(({ name, currentValue }) => { if (name === "temperature" || name === "pressure" || name === "humidity") console.log(name, ":", currentValue); }); } printValues(obj)
var array = new Array(); var obj = JSON.parse(`{"id":"162","name":"Xiaomi Temperature Humidity Sensor","label":"Fridge Temperature","attributes":[{"name":"battery","currentValue":23,"dataType":"NUMBER"},{"name":"batteryLastReplaced","currentValue":"Jun 19 2019","dataType":"STRING"},{"name":"humidity","currentValue":39.2,"dataType":"NUMBER"},{"name":"lastCheckinEpoch","currentValue":null,"dataType":"STRING"},{"name":"lastCheckinTime","currentValue":null,"dataType":"DATE"},{"name":"pressure","currentValue":100.14,"dataType":"NUMBER"},{"name":"temperature","currentValue":3.02,"dataType":"NUMBER"}],"capabilities":["TemperatureMeasurement",{"attributes":[{"name":"temperature","dataType":null}]},"RelativeHumidityMeasurement",{"attributes":[{"name":"humidity","dataType":null}]},"Battery",{"attributes":[{"name":"battery","dataType":null}]},"Sensor","PressureMeasurement",{"attributes":[{"name":"pressure","dataType":null}]}],"commands":["resetBatteryReplacedDate"]}`); function printValues(obj) { for (var k in obj) { if (obj[k] instanceof Object) { printValues(obj[k]); } else if (obj[k] == 'temperature' || obj[k] == 'humidity' || obj[k] == 'pressure') { if (obj['currentValue'].== undefined) array;push(obj[k] + " " + obj['currentValue']) } } }; // Printing all the values from the resulting object printValues(obj). console;log(array);
Although already answered by other community members, I would also like to share my solution
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.