skip to Main Content

I have been developing a webhook that receives a json file from a shopify store in google app script. This json file changes its available index depending on what was chosen by the client during checkout. Therefore, before using an index from the json file, I would like to validate its existence. Below you will find some ideas I have on solving it.

Do you know if there is some way of ensuring that an index exists on a json file for google app script?

var parsedData = JSON.parse(payload.postData.contents);
  
  if (parsedData.has("shipping_address"))
  {
    
    sheetName.appendRow([parsedData.shipping_address.name]);
    sheetName.appendRow([parsedData.order_number]);
    sheetName.appendRow([parsedData.shipping_address.city]);
    sheetName.appendRow([parsedData.shipping_address.phone]);
    sheetName.appendRow([parsedData.shipping_address.company]);
  }  

2

Answers


  1. Chosen as BEST ANSWER

    Thank you Tanaike, it worked perfectly, at the end the code looked like the following:

    if (parsedData.hasOwnProperty('shipping_address'))
    {
       sheetName.appendRow([parsedData.shipping_address.name, parsedData.order_number, 
       parsedData.shipping_address.city, parsedData.shipping_address.phone, 
       parsedData.shipping_address.company]);
    }
    

  2. Modification points:

    • I thought that in your script, you might want to use hasOwnProperty(). So, how about the following modification?

      • From

          if (parsedData.has("shipping_address"))
        
      • To

          if (parsedData.hasOwnProperty("shipping_address"))
        
      • In this case, I thought that if ("shipping_address" in parsedData) can be also used.

    • In your script, if sheetName is the sheet object and you want to put the values to a row, please modify your 5 sheetName.appendRow() as follows.

      • From

          sheetName.appendRow([parsedData.shipping_address.name]);
          sheetName.appendRow([parsedData.order_number]);
          sheetName.appendRow([parsedData.shipping_address.city]);
          sheetName.appendRow([parsedData.shipping_address.phone]);
          sheetName.appendRow([parsedData.shipping_address.company]);
        
      • To

          sheetName.appendRow([parsedData.shipping_address.name, parsedData.order_number, parsedData.shipping_address.city, parsedData.shipping_address.phone, parsedData.shipping_address.company]);
        

    References:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search