Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a 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?

like image 683
tonga Avatar asked Aug 22 '13 18:08

tonga


People also ask

Can JSON array contain different types?

JSON arrays can be of multiple data types. JSON array can store string , number , boolean , object or other array inside JSON array. In JSON array, values must be separated by comma. Arrays in JSON are almost the same as arrays in JavaScript.

Are JSON file consists of different object with different key-value pair?

A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by colon. Each entry (key/value pair) is separated by comma.

Can JSON array have key-value pair?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.


2 Answers

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 } 
like image 191
Ben McCormick Avatar answered Sep 20 '22 02:09

Ben McCormick


It doesn't matter you can mix and match as much as you want.

You could just test it

typeof someItem.example !== 'undefined' // True if `example` is defined.
like image 45
Daniel A. White Avatar answered Sep 22 '22 02:09

Daniel A. White