Convert a JSON file to an array in javascript to visualize the data in ChartsJS

0👍

You can interpret the data by parsing each value and determining the time (hour/minute) and the value of the temperature for the recorded quarter of an hour.

Here are some things to review:

const rawData = {
  "Temp_12:0"  : "26",
  "Temp_12:15" : "20",
  "Temp_12:30" : "25",
  "Temp_12:45" : "25",
  "Temp_13:0"  : "26",
  "Temp_13:15" : "25",
  "Temp_13:30" : "26",
  "Temp_13:45" : "26"
};

const converted = Object.entries(rawData).map(([key, value]) => {
  const [match, hour, minute] = key.match(/^Temp_(\d+):(\d+)$/);
  const date = new Date();
  date.setUTCHours(+hour);
  date.setUTCMinutes(+minute);
  date.setUTCSeconds(0);
  date.setUTCMilliseconds(0);
  return {
    x: date,
    y: +value
  };
});

const data = {
  labels: converted.map(({ x }) => x.toLocaleTimeString('en-US', {
    hour: '2-digit',
    minute: '2-digit',
    timeZone: 'UTC',
    hour12: false
  })),
  datasets: [{
    label: 'Building #1',
    backgroundColor: 'rgb(255, 99, 132, 0.75)',
    borderColor: 'rgb(255, 99, 132)',
    data: converted.map(({ y }) => y),
  }]
};

const config = {
  type: 'line',
  data,
  options: {
    scales: {
      x: {
        title: {
          display: true,
          text: 'Time of Day'
        }
      },
      y: {
        title: {
          display: true,
          text: 'Temperature (°C)'
        }
      },
    },
    plugins: {
      title: {
        text: 'Temperature Tracking',
        display: true
      },
      legend: {
        position: 'right'
      }
    }
  }
};

var myChart = new Chart(document.getElementById('myChart'), config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.min.js"></script>
<div>
  <canvas id="myChart"></canvas>
</div>

👍:0

If your goal is to have an array like ["26", "20"…]:

Object.values({"Temp_12:0": "26",
"Temp_12:15": "20",
"Temp_12:30": "25",
"Temp_12:45": "25",
"Temp_13:0": "26",
"Temp_13:15": "25",
"Temp_13:30": "26",
"Temp_13:45": "26"})

If you want the float values of the strings:

Object.values({"Temp_12:0": "26",
"Temp_12:15": "20",
"Temp_12:30": "25",
"Temp_12:45": "25",
"Temp_13:0": "26",
"Temp_13:15": "25",
"Temp_13:30": "26",
"Temp_13:45": "26"}).map(i => parseFloat(i))

Leave a comment