I tried to create an empty json variable like this;
var myJSON = {
measurements: {} };
and below, I tried to push data into json and write that json into chart.json file but there is an error occured:
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Object
connection.query('SELECT Temprature,Humidity, Time from miTemp1', function (error, results, fields) {
if (error) throw error;
let i = 0, j = 0;
console.log(typeof (results))
while (i < results.length) {
let myDate = new Date(results[i].Time * 1000);
// console.log('Temp: ' + results[i].Temprature, 'Humidty:' + results[i].Humidity, 'Time: ' + myDate.toLocaleString());
measurements[i] = results[i];
i += 510;
j++;
}
myJSON.measurements = JSON.stringify(measurements);
console.log(typeof(myJSON));
console.log(myJSON);
console.log(new Date().toLocaleString() + ' Number of measurement: ' + j);
try {
fs.writeFileSync('./chart.json', myJSON);
console.log("JSON data is saved.");
} catch (error) {
console.error(error);
}
});
If I create json variable like var myJSON = {} there is no problem. Why this is happening? Thanks for helps ^-^
EDIT:
here is my JSON's data.
{
"0": {
"Temprature": 25.88,
"Humidity": 43,
"Time": 1628164626
},
"510": {
"Temprature": 26.22,
"Humidity": 45,
"Time": 1628169522
},
SOLUTION:
All I need to do is changing myJSON.measurements = JSON.stringify(measurements); to myJSON.measurements = measurements; and stringify the entire object.
You can't just write an object to a file. You need to serialize it first with JSON.stringify():
fs.writeFileSync('./chart.json', JSON.stringify(myJSON));
You also don't need to serialize the measurements property, since you serialize the whole object. You can replace this:
myJSON.measurements = JSON.stringify(measurements);
with this:
myJSON.measurements = measurements;