I have the following JSON structure but am wondering if there would be any way to simplify it further. Can 'ingredient' and 'quantity' be removed from all the entries somehow to help reduce it?
var cooking = {
"recipes" : [
{
"name":"pizza",
"ingredients" : [
{
"ingredient" : "cheese",
"quantity" : "100g"
},
{
"ingredient" : "tomato",
"quantity" : "200g"
}
]
},
{
"name":"pizza 2",
"ingredients" : [
{
"ingredient" : "ham",
"quantity" : "300g"
},
{
"ingredient" : "pineapple",
"quantity" : "300g"
}
]
}
]
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With