9

Below are 3 JSON Array structure formats...

The first one, the one outlined at JSON.org, is the one I am familiar with:

Format #1

{"People": [
  {
    "name": "Sally",
    "age": "10"
  },
  {
    "name": "Greg",
    "age": "10"
  }
]}

The second one is a slight variation that names the elements of the array. I personally don't care for it; you don't name elements of an array in code (they are accessed by index), why name them in JSON?

Format #2

{"People": [
  "Person1": {
    "name": "Sally",
    "age": "10"
  },
  "Person2": {
    "name": "Greg",
    "age": "10"
  }
]}

This last one is another variation, quite similar to Format #2, but I have a hunch this one is incorrect because it appears to have extra curly braces where they do not belong.

Format #3

{"People": [
  {
    "Person1": {
      "name": "Sally",
      "age": "10"
    }
  },
  {
    "Person2": {
      "name": "Greg",
      "age": "10"
    }
  }
]}

Again, I'm confident that Format #1 is valid as it is the JSON Array format outlined at JSON.org. However, what about Format #2 and Format #3? Are either of those considered valid JSON? If yes, where did those formats come from? I do not see them outlined at JSON.org or on Wikipedia.

2
  • Actually, they're all invalid: jsonlint.com Commented Jan 2, 2013 at 22:30
  • Oops, I'm missing some punctuation... fixing. Commented Jan 2, 2013 at 22:32

2 Answers 2

11

Both #1 and #3 are (nearly - there are commas missing) valid JSON, but encode different structures:

  • #1 gives you an Array of Objects, each with name and age String properties
  • #3 gives you an Array of Objects, each with a single Object property, each with name and age String properties.

The #2 is invalid: Arrays (as defined by [ ... ]) may not contain property names.

Sign up to request clarification or add additional context in comments.

Comments

1

Solution For Format#1 By default:

array=[];
object={};

JSON Code:

var Json = {
    People:[]
};
Json.People.push({
     "name": "Sally",
     "age": "10"                        
});
Json.People.push({
     "name": "Greg",
     "age": "10"                        
});

JSON Result:

{"People": [ { "name": "Sally", "age": "10" }, { "name": "Greg", "age": "10" } ] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.