Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
How to name a JSON object and writing it into a .json file?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!