Skip to content
Advertisement

Access nested JSON with month numbers

i got an json file with monthly values. i need to access these. I am not able to archive this. Maybe i just make an mistake.

{"sales":
  {
    "total_sales":"999.99",
    "totals":
       {
         "2020-10-01":
             {
               "sales":"9.99",
             }
       }
  }
}

How can i get the value from the second “sales” with 9.99?

I use JS to get the total_sales. This works.

I really need you help for this.


For more clearence: The JSON-File is an original from Woocommerce.

I implement the Json with the original API and need the sales for every month.

I already tried it with Object.keys but it does not work. i only get the (2020-01-01) Names but not the nested values.

Here is the information about the original JSON File: https://github.com/woocommerce/woocommerce-rest-api-docs/blob/master/source/includes/v2/_reports.md

Bad thing is the date string as key.

Maybe there is a tricky way to archive the result.

Advertisement

Answer

So, let’s say you have data with the variable name salesReport like this:

{
  "sales": {
    "totals": {
      "2015-01-18": {
        "sales": "-17.00",
      },
      "2015-01-21": {
        "sales": "597.10",
      },
      "2015-02-18": {
        "sales": "32.00",
      },
      "2015-03-12": {
        "sales": "22.00",
      },
    },
  }
}

Then you want to access the sales.totals data for each date without having to know the key details. Furthermore, if you need to store the key (in this case the date) along with their respective values then you can convert them into entries first using Object.entries as in the following code:

const salesReportTotalsEntries = Object.entries(salesReport.sales.totals);

Then you can access the sales data on each date using

salesReportTotalsEntries[0][1].sales
salesReportTotalsEntries[1][1].sales

And the last step is that you can use Array.reduce to sum each totals sales data based on the data for each month. Here’s the complete code:

const salesReport = {
  "sales": {
    "totals": {
      "2015-01-18": {
        "sales": "-17.00",
      },
      "2015-01-21": {
        "sales": "597.10",
      },
      "2015-02-18": {
        "sales": "32.00",
      },
      "2015-03-12": {
        "sales": "22.00",
      },
    },
  }
};

const salesReportTotalsEntries = Object.entries(salesReport.sales.totals);
const salesReportTotalsByMonths = salesReportTotalsEntries.reduce((a, v) => {
  const currentMonth = v[0].split('-')[1];
  if (!a[currentMonth]) {
    a[currentMonth] = Number(v[1].sales);
    return a;
  }
  a[currentMonth] += Number(v[1].sales);
  return a;
}, {});

console.log(`Total Sales Report in January is ${salesReportTotalsByMonths['01']}`);
console.log(`Total Sales Report in February is ${salesReportTotalsByMonths['02']}`);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement