Search code examples
jsonata

Is it possible to exclude certain fields using JSONATA?


Using JSONATA, is it possible to exclude certain fields that are nested in a deep structure without using object construction? For example, with the following object

{
    "collection": [
        {
            "id": "ABC",            
            "learningunit": {
                "metadata": {
                    "show": true,
                    "unitType": {
                        "code": "U",                        
                        "value": "Unit"
                    }                   
                }
            }
        },
        {
            "id": "UYE",            
            "learningunit": {
                "metadata": {
                    "show": false,
                    "unitType": {
                        "code": "C",                        
                        "value": "COURSE"
                    }                   
                }
            }
        }
    ]
}

can we exclude the field "show" and "value" in order to get the following result.

{
    "collection": [
        {
            "id": "ABC",            
            "learningunit": {
                "metadata": {                   
                    "unitType": {
                        "code": "U"                     
                    }                   
                }
            }
        },
        {
            "id": "UYE",            
            "learningunit": {
                "metadata": {                   
                    "unitType": {
                        "code": "C"                     
                    }                   
                }
            }
        }
    ]
}

FYI, the following object construction expression does the job but it is cumbersome to write if the object is complex.

{"collection":collection.
    {
    "id": id,
    "learningunit": learningunit.
        { 
            "metadata": metadata. 
            {
                "unitType": unitType.
                {
                    "code": code
                }
            }
        }
    }
} 

Solution

  • You can make use of the transform operator and remove all 'value' and 'show' fields from the nested structure:

    $$ ~> | ** | {}, ['show', 'value'] |
    

    See it on the live Stedi playground: https://stedi.link/Usc1tpg

    Note that if you need to clear those on a specific path only, you can also do it more surgically:

    $$
      ~> | *.learningunit.metadata | {}, ['show'] |
      ~> | *.learningunit.metadata.unitType | {}, ['value'] |
    

    Playground: https://stedi.link/Bh8cUiM