Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I know that in most programming scenarios, the preference is for empty collections to null collections when there are 0 elements. However, most languages that consume JSON (like JavaScript) will treat empty lists/objects as true and null ones as false. For example this would be both true and an object in JavaScript:

{
    "items_in_stock": {"widgets":10, "gadgets": 5}
}

But this is also true:

{
    "items_in_stock": {}
}

And this is false:

{
    "items_in_stock": null
}

Is there a convention on empty objects/lists for JSON? And what about for numbers, booleans, and strings?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
131 views
Welcome To Ask or Share your Answers For Others

1 Answer

It is good programming practice to return an empty array [] if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}.

Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.

This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.

Here's a link to that part of his book:

http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...