Home > Net >  Unnest a nested JSON object
Unnest a nested JSON object

Time:03-23

I have a nested JSON object below.

    var payload = {
      "name" : {
        "first" : "I am a",
        "last" : "Customer"
      },
      "product_info": {
        "name" : "Product 1",
        "category" : {
          "id" : "123456789",
          "name" : "C1",
          "sub_category" : {
            "id" : "321654987",
            "name" : "SC1"
          },
        }
      }};

    var param = JSON.stringify(payload);

How can I unnest the JSON object, so I can have the JSON object as below?

    var result = {
      "name.first" : "I am a",
      "name.last" : "Customer",
      "product_info.name" : "Product 1",
      "product_info.category.id" : "123456789",
      "product_info.category.name" : "C1",
      "product_info.category.sub_category.id" : "321654987",
      "product_info.category.sub_category.name" : "SC1"
    }

I was trying to use the Object.keys(param).length to check how many nested object there are, but if there isn't a nested object, it will return the length of the value.

Any suggestion would be appreciated.

CodePudding user response:

Try the code below to flatten your JSON object at any nesting level:

function myFunction(){
  var payload = {
      "name" : {
        "first" : "I am a",
        "last" : "Customer"
      },
      "product_info": {
        "name" : "Product 1",
        "category" : {
          "id" : "123456789",
          "name" : "C1",
          "sub_category" : {
            "id" : "321654987",
            "name" : "SC1"
          },
        }
      }};
      
  const flattenJSON = (payload = {}, res = {}, extraKey = '') => {
   for(key in payload){
      if(typeof payload[key] !== 'object'){
         res[extraKey   key] = payload[key];
      }else{
         flattenJSON(payload[key], res, `${extraKey}${key}.`);
      };
   };
   return res;
};
console.log(flattenJSON(payload));
};

Basically it's rebuilding your JSON object and assigning it to a new variable that is flattened object to the very first level. The process works by iterating through the object and if it's the last parameter on the object it will add a new key with value. The key is the appended keys of all keys that it goes through.

This should return the unnested JSON objectenter image description here

Reference link: https://www.tutorialspoint.com/flattening-a-json-object-in-javascript

CodePudding user response:

Traverse the object

function myFunction() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const s = '{"name":{"first":"Iama","last":"Customer"},"product_info":{"name":"Product1","category":{"id":"123456789","name":"C1","sub_category":{"id":"321654987","name":"SC1"}}}}';
  const obj = JSON.parse(s);
  traverse1(obj, process1);
}

function traverse1(o, func) {
  for (var i in o) {
    func.apply(this, [i, o[i]]);
    if (o[i] !== null && typeof (o[i]) == "object") {
      traverse(o[i], func);
    }
  }
}

function process1(key, value) {
  if (typeof (value) == "object") {
    Logger.log(key);
  } else {
    Logger.log("%s: %s ", key, value);
  }
}

Execution log
9:08:32 PM  Notice  Execution started
9:08:32 PM  Info    name
9:08:32 PM  Info    first: Iama 
9:08:32 PM  Info    last: Customer 
9:08:32 PM  Info    product_info
9:08:32 PM  Info    name: Product1 
9:08:32 PM  Info    category
9:08:32 PM  Info    id: 123456789 
9:08:32 PM  Info    name: C1 
9:08:32 PM  Info    sub_category
9:08:32 PM  Info    id: 321654987 
9:08:32 PM  Info    name: SC1 
9:08:33 PM  Notice  Execution completed
  • Related