Represent missing values ​​as null or not at all in JSON

I am creating a web services API using JSON as the data language. By creating a structure for the data returned from the service, I am having some problems resolving problems with missing values.

Consider this example: I have a product in my online store whose price is not yet known, possibly because the product has not yet been released. Include price: null (as shown below) or just omit the price property in this element?

 { name: 'OSX 10.6.10', brand: 'Apple', price: null } 

My main concern is to make the API as easy to use as possible. The explicit empty value makes it clear that the price can be expected on the product, but on the other hand, it looks like wasted bytes. There may be a whole bunch of properties that are completely unrelated to this particular product, and also apply to other products - should I show them as explicitly null ?

 { name: 'OSX 10.6.10', price: 29.95, color: null, size: null } 

Are there any “best practices” in web service design that support explicit or implicit null values? Any de facto standard? Or does it completely depend on the use case?

+6
source share
2 answers

FWIW, my personal opinion:

Include price: null (as shown below) or just omit the price property of this item?

I would set the values ​​of the "standard" fields to null . Although JSON is often used with JavaScript, and missing properties can be handled in the same way as those set to null, this should not be the case for other languages ​​(e.g. Java). Before you first check to see if a field is present, it seems uncomfortable. Setting the values ​​to null , but the availability of fields will be more consistent.

There may be a whole bunch of properties that are completely unrelated to this particular product, while relevant to other products. Should I show them as explicitly null ?

I would include only those fields that relate to the product (for example, not pages for the CD). The client’s task is to properly handle these “optional” fields. If you do not have a value for a specific field that relates to a product, set it also to null .


As already mentioned, the most important thing is to be consistent and clearly define which fields can be expected. You can reduce the size of the data using gzip compression.

+3
source

I don’t know what “best practice” is. But I usually don’t send fields that I don’t need. When I read the answer, I check if the value exists:

 if (res.size) { // response has size } 
0
source

Source: https://habr.com/ru/post/893256/


All Articles