31

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?

4
  • 7
    Yes, json arrays can contain any valid json string: objects with different key/value pairs, other arrays, numbers, strings, booleans all in the same array. Commented Aug 22, 2013 at 18:52
  • go here to test any javascript you want: jsconsole.com Commented Aug 22, 2013 at 18:55
  • Not only it is pretty old, the practice it supports was wrong already 13 years before the article was published. Commented Aug 22, 2013 at 18:57
  • @asawyer OK I'll remove mine too :) Commented Aug 22, 2013 at 18:57

4 Answers 4

26

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. What is the best way to test if the JSON array contains homogeneous objects or not?
@tonga you will not be able to test the homogeneity of the array in that way. You can only know if the array is homogeneous until you have finished processing all of its items
the answer is correct, but the statement about XML is incorrect ... XML is based on a well known spec and very clear definition but its up to you if you want to use a schema or not, its an option.
6

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.

3 Comments

Thanks. Can this approach test if the array contains homogeneous objects or not? What is the best way to test the homogeneity of a JSON array using JavaScript?
@tonga it would be iterating it.
So there is no single built-in JS function to test the array?
5

It's perfectly valid JSON. Personally I prefer this syntax better, because it reads easier:

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

As to answer your second question, you can read data from a JSON string by using var data = JSON.parse(datastring);. Then simply use it by calling data.property.secondlevel. Any variable can be an object, array, string or number, allowing for nested structures.

3 Comments

If you downvote, let me at least know why. I've read the question and don't see the point of downvoting this?
Maybe suggest an edit to the original question for the reformatting? Not my downvote though...
(For those who are confused: the formatting in the question was updated)
3

You are free to do what you want with the contents of the array. Jus remember about this before you try to iterate an access properties of each item in your array.

one thing: you won't be able to deserialize this to anything else than an array of object in your server side, so don't have surprises later.

as a hint, maybe you could include a common field in the objects specifying the "type" so later is easy to process.

var array = [{"type":"fruit", "color":"red"},
{"type":"dog", "name":"Harry"}];

var parser = {
    fruit:function(f){
   console.log("fruit:" + f.color);
    },
    dog: function(d){
    console.log("dog:"+d.name);
    }};

for(var i=0;i<array.length;i++){
    parser[array[i].type](array[i]);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.