Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  180] [ 4]  / answers: 1 / hits: 40184  / 11 Years ago, thu, august 22, 2013, 12:00:00

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?


More From » arrays

 Answers
103

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
}

[#76204] Thursday, August 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
coby

Total Points: 27
Total Questions: 102
Total Answers: 97

Location: Honduras
Member since Wed, Jul 14, 2021
3 Years ago
;