Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda