tonga tonga - 2 months ago 7
Javascript Question

Can JSON array contain Objects of different key/value pairs?

Can a JSON array contain Objects of different key/value pairs. From this tutorial, the example given for JSON array consists of Objects of the same key/value pair:

{
"example": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}


If I want to change it to have different key/value pairs inside the JSON array, is the following still a valid JSON?

{
"example": [
{ "firstName":"John", "lastName":"Doe" },
{ "fruit":"apple" },
{ "length":100, "width":60, "height":30 }
]
}


Just want to confirm this. If so, how can I use JavaScript to know if the JSON
"example"
field contains the first homogeneous objects or the second heterogeneous objects?

Answer

You can use any structure you like. JSON is not schema based in the way XML is often used and Javascript is not statically typed.

you can convert your JSON to a JS object using JSON.parse and then just test the existence of the property

var obj = JSON.parse(jsonString);
if(typeof obj.example[0].firstName != "undefined") {
   //do something
}
Comments