How to parse JSON into an array (for google scripts)

I am using Google Scripts, and currently have the following JSON formatted string that I am able to get from the API of a crypto site.

{"sellerCommission":0,"updateTime":1613134493127,"accountType":"SPOT","balances":[{"asset":"BTC","free":"0.00000000","locked":"0.00000000"},{"asset":"ETH","free":"0.05000000","locked":"0.00000000"},{"asset":"OXT","free":"1.00000000","locked":"0.00000000"},{"asset":"ZEN","free":"2.00000000","locked":"0.00000000"}],"permissions":["SPOT"]}

I would like to take this and convert this to an array. I’d like the array to be in the format of [asset, free, locked], and I would only like it to display in the array if the value of free is >0. What is the best way to accomplish this?

24 thoughts on “How to parse JSON into an array (for google scripts)”

  1. function myfunction() {
      const jsn='{"sellerCommission":0,"updateTime":1613134493127,"accountType":"SPOT","balances":[{"asset":"BTC","free":"0.00000000","locked":"0.00000000"},{"asset":"ETH","free":"0.05000000","locked":"0.00000000"},{"asset":"OXT","free":"1.00000000","locked":"0.00000000"},{"asset":"ZEN","free":"2.00000000","locked":"0.00000000"}],"permissions":["SPOT"]}';
      const obj=JSON.parse(jsn);
      let oA=[];
      obj.balances.forEach((o,i)=>{
        if(o.free>0) {
          oA.push([o.asset,o.free,o.locket]);
        }
      });
      console.log(JSON.stringify(oA));
    }
    
    Execution log
    9:49:40 PM  Notice  Execution started
    9:49:41 PM  Info    [["ETH","0.05000000",null],["OXT","1.00000000",null],["ZEN","2.00000000",null]]
    9:49:41 PM  Notice  Execution completed
    
    Reply

Leave a Comment