I have a nested JSON dataset and would like to extract and print certain values from it.
I can extract and print the entire JSON components, can get the values for the top level of data, but I don't know how to get access to the individual components of the next level of data.
My code is below. It correctly prints the values for "age" and "measurements"
var json = `{
    "age":"84",
    "measurements":"5235", 
    "sensordatavalues":
    [
        {"value_type":"P1", "value":"5.50"},
        {"value_type":"P2", "value":"1.65"},
        {"value_type":"temperature", "value":"18.21"},
        {"value_type":"humidity", "value":"66.75"},
        {"value_type":"pressure", "value":"101171.75"}
    ]
}`;
// 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>");
    };
  }
};
// Print all the values from the resulting object
printValues(obj);
document.write("<hr>");
// Print some of the individual values
document.write(obj.age + "<br>"); // Prints: Age
document.write(obj.measurements + "<br>"); // Prints: Measurements
document.write(obj.sensordatavalues.P1 + "<br>"); // Should print P1 value
document.write(obj["sensordatavalues"].P2 + "<br>"); // Should print P2 value
document.write(obj["sensordatavalues"]["humidity"] + "<br>"); // Should print Humidity
document.write(obj.pressure + "<br>"); // Should print Pressurebut is not able to correctly parse the data for "humidity" and "pressure" (or other values) from the nested JSON data. I've tried a few different ways but seems like I'm missing an important step.
Any help would be appreciated.
 
     
    
"); // Prints P1 Value` – Mehdi Nov 06 '20 at 08:28