Simplifying JSON structure Simplifying JSON structure json json

Simplifying JSON structure


Yes, you can simplify that quite a bit:

var recipes = {    "pizza": {        "cheese": "100g",        "tomato": "200g"    },    "pizza 2": {        "ham": "300g",        "pineapple": "300g"    }}

An explanation:

  • The top level of your example is a single-item object: {"recipes": <...>}. Unless this is a simplified version of an object that will actually have other items in it, that's redundant. Your code knows what it's sending/recieving, so there's no extra information there.

  • The value of your {"recipes": <...>} object is an array of two-item objects, with the keys "name" and "ingredients". Whenever you have an array like this, it makes more sense (and is more compact) to replace it with an object. As a rule of thumb:

    If the keys in an array of objects can be replaced by "key" and "value" and still make sense, replace the array with a single {"key_name": <value>, ...} object.

  • The same rule applies to your [{"ingredient": <...>, "quantity": <...>}, ...] array: each object can be replaced by a key-value pair and continue to make sense.

The end result is that this representation of the information is 87 characters in length (with extraneous whitespace removed), compared to your original's 249 characters - a 65% reduction.


Definitely. One way would be :

var cooking = {        "recipes" : [            {                "name":"pizza",                "ingredients" : [                    "cheese",                      "tomato"                    ],                   "quantities" : [ // Have to be in order of ingredients                        "100g",                        "200g"                ]            }        ]  }

Or

var cooking = {    "recipes" : [        {            "name":"pizza",            "ingredients" : [ // Putting ingredient and quantity together                "cheese:100g",                  "tomato:200g"                ]        }    ]}

Since they are all pizzas you can remove the name.

var cooking = {    "recipes" : [        {            "ingredients" : [                "cheese:100g",                  "tomato:200g"                ]        },        {            "ingredients" : [                "ham:100g",                  "pineapple:200g"                ]        }    ]}


Hope this simplifies it for you ! Json must be written in a way so that its minimal and comprehensible for both computers and humans.

var cooking = {            "recipes" :            [                       {                "name":"pizza",                "cheese": "100g"                "tomato": "200g"            }                       ,            {                "name":"pizza 2",                "ham": "300g"                "pineapple": "300g"            }            ]            }    };