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?
It’s not possible in JSON. In JavaScript, however, there are a few things you can do. You can provide a
toStringmethod to be used when the object is converted to a string:You can also use a
Stringobject:The latter acts more like a string, but it uses a
Stringobject, which can be frustrating at times and is usually bad practice.