HughP HughP - 29 days ago 10
JSON Question

Access text from JSON object built with dot notation

Just learning how to build and read json objects for a pet adoption site I'm working on as a hobby project. A friend suggested I build one like this:

var userData = {};
userData['dogs'] = {};
userData.dogs['Spot'] = {};
userData.dogs.Spot['color'] = 'black';
userData.dogs.Spot['weight'] = '24lbs';
userData.dogs.Spot['location'] = 'Washington';
userData.dogs.Spot['comments'] = 'this is a long string of text';


I have figured out how to stringify this, store it, retrieve it and parse it but I can't figure out how to access the individual pieces of info (weight for instance). Is it standard to build up the object like this with dots from userData, to userData.dogs to userData.dogs.spot? And how do I access each of the properties?

Answer Source
var userData = {
  dogs: {
     spots: {
      color: 'black',
      weight: 'x lbs',
      anotherKey: 'some value'
   }
 };

what you do is the same as above. If you are a beginner you can read more about JavaScript Object here: https://www.w3schools.com/js/js_objects.asp. If you are more intermediate, you can read here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object