0

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 Pressure

but 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.

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Mehdi
  • 1
  • 1
  • 1
    If you want to get the P1 value, the steps you have to take is: 1. Access the sensordatavalues value (which is a list), 2. Find the item in that list who's value_type key has the value "P1", 3. get the "value" of that object. What that looks like is `json.sensordatavalues.find(subObj => subObj.value_type === 'P1').value` I'm using the Array.find() function to find the needed item in the array. The "=>" is an "arrow function", which is mostly shorthand. You can read up about them on doc sites to learn more. – Scotty Jamison Nov 06 '20 at 05:18
  • Very helpful, Scotty. Thanks. – Mehdi Nov 06 '20 at 05:36
  • 1
    After a bit of search, the easiest method to achieve what I wanted is to do the following: `document.write(obj.sensordatavalues[0].value + "
    "); // Prints P1 Value`
    – Mehdi Nov 06 '20 at 08:28

0 Answers0