API Connect

API Connect

Join this online group to communicate across IBM product users and experts by sharing advice and best practices with peers and staying up to date regarding product enhancements.

 View Only
Expand all | Collapse all

JSON NULL fields to be removed

  • 1.  JSON NULL fields to be removed

    Posted Thu August 11, 2022 12:34 PM
    Hi,

    Could you please help to provide gateway script to remove NULL fields in JSON message recursively.

    {
    "name":"hello",
    "address":NULL
     [
        { Innervalue : NULL,
        innername : "one"
       },
      { Innervalue : NULL,
        innername : "one"
       },
    ],
    }

    ------------------------------
    santhoshkumar surisetty
    ------------------------------


  • 2.  RE: JSON NULL fields to be removed

    Posted Tue September 13, 2022 05:42 PM
    Edited by Christopher Phillips Tue September 13, 2022 05:44 PM
    Here is a quick sample, i tested this on the native api gw



    let js = {
    "name":"hello",
    "address":null,
    obj:[
    { "Innervalue" : null,
    "innername" : "one"
    },
    { Innervalue : null,
    innername : "one"
            }
    ]
    }

    let depthCounterMax=10;
    let depthCounter = 0

    function removeNULL(obj) {
    Object.keys(obj).forEach((key)=>{
    if (obj[key] == null ) {
    delete obj[key]
            }
            else if (typeof obj[key] == "object" && obj[key].length > 0) {
              if (depthCounter < depthCounterMax ) {
    depthCounter++
    obj[key].forEach((e)=>{
    removeNULL(e)
    })
    }
           }
    else if (typeof obj[key] == "object" ) {
    if (depthCounter < depthCounterMax ) {
    depthCounter++
    removeNULL(obj[key])
    }
    }
      })
    }
    removeNULL(js)
    context.set("message.body",js)

    ------------------------------
    Chris Phillips

    IBM STSM & Master Inventor
    Integration Architect
    ------------------------------