Escribir un objeto JSON en un archivo JSON con fs.writeFileSync


Estoy intentando escribir un objeto JSON en un archivo JSON. El código se ejecuta sin errores, pero en lugar de escribir el objeto en sí, todo lo que se escribe en el archivo JSON es:

[object Object]

Este es el código que realmente hace la escritura:

fs.writeFileSync('../data/phraseFreqs.json', output)

'output' es un objeto JSON, y el archivo ya existe. Por favor, hágamelo saber si se requiere más información.

Author: Romulus3799, 2017-02-11

3 answers

No creo que deba usar Synchronous es lo bueno, Asynchronously escribir datos en un archivo es mejor también stringify el output si es un object.

Nota: Si output es una cadena, especifique la codificación. y recuerde las opciones flag también.:

const fs = require('fs');
const content = JSON.stringify(output);

fs.writeFile("/tmp/phraseFreqs.json", content, 'utf8', function (err) {
    if (err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 
 40
Author: akinjide,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-11 17:42:38

Necesita stringify el objeto.

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output));
 40
Author: Kamal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-22 03:16:47

Haga que json sea legible para humanos con:

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output,null,4));

 13
Author: Timelot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-19 05:07:55