ThomasReggi
ThomasReggi

Reputation: 59475

JSON perspective

Lets say I have a JSON document / JavaScript object that looks like this:

var animal = {
  "squirrel": "Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae."
}

In JavaScript, this would happen:

console.log(animal.squirrel) //Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae

Let's say I wanted to add the rank object in:

var animal = {
  "squirrel": {   
    "rank": {
      "Kingdom": "Animalia",
      "Phylum": "Chordata",
      "Class": "Mammalia",
      "Order": "Rodentia",
      "Suborder": "Sciuromorpha",
      "Family": "Sciuridae"
    }
  }
}

The rank would be accessible like so:

animal.squirrel.rank

But I still want the top-level of the animal.squirrel object to be a string containing the sentence above.

Is this possible?

Upvotes: 2

Views: 86

Answers (2)

techn1cs
techn1cs

Reputation: 46

As the others said, this isn't possible in any object context, so you'll need to handle everything as accessible parts on/in the object.

var animal = {
  "squirrel": {
    "info": "Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae.",
    "rank": {
      ...
    }
  }
}

And, I suppose unrelated, you could setup quick accessors for commonalities.

function getAnimalInfo(animalName) {
  if (!animal[animalName]) return "No info for: " + animalName;

  return animal[animalName].info;
}

So,

console.log(getAnimalInfo("squirrel")); //Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae

Upvotes: 1

Ry-
Ry-

Reputation: 225044

It's not possible in JSON. In JavaScript, however, there are a few things you can do. You can provide a toString method to be used when the object is converted to a string:

var animal = {
  "squirrel": {   
    "rank": {
      "Kingdom": "Animalia",
      "Phylum": "Chordata",
      "Class": "Mammalia",
      "Order": "Rodentia",
      "Suborder": "Sciuromorpha",
      "Family": "Sciuridae"
    },
    toString: function() {
      return "Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae.";
    }
  }
};

You can also use a String object:

var animal = {
    squirrel: new String("Squirrels belong to a large family of small or medium-sized rodents called the Sciuridae.")
};

animal.squirrel.rank = {
    "Kingdom": "Animalia",
    "Phylum": "Chordata",
    "Class": "Mammalia",
    "Order": "Rodentia",
    "Suborder": "Sciuromorpha",
    "Family": "Sciuridae"
};

The latter acts more like a string, but it uses a String object, which can be frustrating at times and is usually bad practice.

Upvotes: 5

Related Questions