简体   繁体   中英

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?

  1. No, it is not standard to build the object like that because that's using iterative steps (ie, a program ), whereas JSON is a declarative literal (remember: J ava S cript O bject N otation ). You can express the same final object like so:

     userData = { "dogs": { "Spot": { "color": "black", "weight": "241lbs", "location": "Washington", "comments": "this is a big dog, 241lbs, wow" } } }; 

    Note that "pure" JSON requires double-quote delimited keys. Whereas an in-script object-literal can use standard identifiers without quotes.

  2. You can access them using dotted notation. You only need to use the string-indexer property syntax if your objects have keys that do not conform to JavaScript identifier restrictions (eg no spaces, punctuation, must start with a letter, etc):

    console.log( userData.dogs.Spot.color ); console.log( userData.dogs.Spot.comments );

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM