1

I have a Javascript object that I change by iterating through it. I want to save it as a JSON object. But how do I get the new object? If I console.log it there are two problems: First, it could be too long for the console. Second, the console removes the strings for the keys.

What is the best way to handle this?

I would like to get this JSON and copy it into another file. I've tried using fs:

var fs = require('fs');
fs.writeFile("data/datafile.json", dataObject, function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
});

But it just writes this to the datafile.json file:

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Any ideas or best practices?

anon
  • 2,143
  • 3
  • 25
  • 37
  • 1
    Please make your description more clear. Firstly, JSON is a string, so you can't iterate through it unlike you said. – Robo Robok Oct 15 '15 at 22:11
  • It is considered best practice to read manuals, tutorials and help sections. You should start with [ask], then go [here](https://nodejs.org/api/fs.html#fs_fs_writefile_filename_data_options_callback) and think if the value your using `dataObject` matches the expected input (my money is on: "doesn't match") – Amit Oct 15 '15 at 22:16
  • Either you log the error and return false, or you return the error itself, but you have no interest in returning the result of console.log(); – Benjamin C. Oct 15 '15 at 22:17

1 Answers1

2

You should use the json sringify option:

//Replace
fs.writeFile("data/datafile.json", dataObject, function(err)...

//with:
fs.writeFile("data/datafile.json", JSON.stringify(dataObject), function(err)...

if you simply doing it to clone, you can use one of these methods: What is the most efficient way to deep clone an object in JavaScript?

if you want just to view it, you can console.log the stringified JSON and copy paste it into online json viewer. (if its too big you can save to file as you did and upload the file to an online viewer)

Community
  • 1
  • 1
Ziv Weissman
  • 4,400
  • 3
  • 28
  • 61