0

I'm building my first API which outputs in JSON, and was wondering: If one of the parameters is empty, is it best to still include that parameter name with an empty value, or not include it at all? For example, if a certain product has batteries it would normally output

"batteries": [
            {
                "device": "Vehicle",
                "number": "4",
                "type": "AA",
                "included": "Not Included"
            },
            {
                "device": "Remote",
                "number": "2",
                "type": "AAA",
                "included": "Not Included"
            }
        ],

If there are no remote batteries, should I just not include that second section? What if there aren't batteries at all, should I remove the whole battery node?

Jon
  • 846
  • 1
  • 8
  • 25

2 Answers2

4

From the perspective of the json interpreter it won't matter. You should send the JSON however you want the consumer to reconstruct your objects... Do you want the consumer to have a "Remote" object indicating there are no batteries?

Your example doesn't look like an empty node to me, it looks like meaningful data!

For actually empty nodes it may only matter if you need to keep the serialized object as small as possible (for whatever reason) or if you need to have something else besides JSON look at the serialized object later.

In my personal opinion from an API I like to see all meaningful nodes populated because it gives me an idea of the possibilities of the API.... "Oh, I see, so some of them have remotes and include batteries and this API can tell me that!"

Matthew
  • 10,244
  • 5
  • 49
  • 104
0

In Javascript, you can treat an absent property in almost the same way you would trean a property set to null:

> a_unset = {}
> a_null = {a: null}
> a_null.a == a_unset.a
true
> a_null.a ? 1 : 0
0
> a_unset.a ? 1 : 0
0

Therefore in JSON, which is based on Javascript and most often consumed by Javascript code, it is customary to omit empty values.

But this is not a hard rule. JSON does provide the null value, so if you think your client code or target users would need to know that a property is there but unset, null might be a good choice. Otherwise just omit it, you will save space.

Tobia
  • 17,856
  • 6
  • 74
  • 93