Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Array Structure Variations

Tags:

json

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.

like image 851
MikeS Avatar asked Jan 02 '13 22:01

MikeS


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.

What is the difference between {} and [] in JSON?

{} denote containers, [] denote arrays.

How do I make a JSON object with multiple arrays?

The JSON data is an object (basically an associative array). Indexed arrays use square brackets, [0,1,2] , while associative arrays use curly braces, {x:1,y:2,z:3} . Any of the data within the outermost object can be either type of array, but the outermost object itself has to use curly braces.

What are {} in JSON?

JSON has the following syntax. Objects are enclosed in braces ( {} ), their name-value pairs are separated by a comma ( , ), and the name and value in a pair are separated by a colon ( : ). Names in an object are strings, whereas values may be of any of the seven value types, including another object or an array.


1 Answers

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.

like image 85
Eugen Rieck Avatar answered Oct 14 '22 07:10

Eugen Rieck