'json array with null

Below is the JSON that is parsed to validate PUT request body:

{
    "requestKey": "whatever",
    "shoppingList": []
}

As part of testing, we are seeing another scenario coming, which is also a valid JSON:

{
    "requestKey": "whatever",
    "shoppingList": [null]
}

[] signifies empty shopping list. What does [null] signify?

How [null] different from []? for shoppingList



Solution 1:[1]

null in this case and as referenced in RFC 7159 means that the shoppingList is an array containing one primitive null value.

At least semantically it should yield in (Source example is in Java):

shoppingList.get(0) -> null 

Whereas an empty array should yield in:

shoppingList.get(0) -> IndexOutOfBoundsException

Which is exactly the behaviour you see in the current version of Google Chrome:

let myObj = {
    "requestKey": "whatever",
    "shoppingList": [null]
};
undefined
myObj
{requestKey: 'whatever', shoppingList: Array(1)}requestKey: "whatever"shoppingList: Array(1)0: nulllength: 1[[Prototype]]: Array(0)[[Prototype]]: Object
let myObj = {
    "requestKey": "whatever",
    "shoppingList": []
};
undefined
myObj
{requestKey: 'whatever', shoppingList: Array(0)}requestKey: "whatever"shoppingList: [][[Prototype]]: Object

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 maio290