0

I have this code:

var gameon = 1;
var fighter1 = {"userid":"97","username":"john","items":{},"ailments":{}};
var fighter2 = {"userid":"91","username":"james","items":{},"ailments":{}};
var resume = 30;

all = {gameon:gameon,fighter1:fighter1,fighter2:fighter2,resume:resume,inturn:fighter1,outturn:fighter2};
    
fs.writeFileSync(file, util.inspect(all, { showHidden: true, depth: null }), { encoding: 'utf8', flag: 'w' });

I expect to have the next output written to file:

{
  "gameon":1,
  "fighter1":{
    "userid":"97",
    "username":"john",
    "items": {},
    "ailments":{}
   },
   "fighter2":{
     "userid":"91",
     "username":"james",
     "items":{},
     "ailments":{}
    },
    "resume":"",
    "inturn":{
      "userid":"97",
      "username":"john",
      "items":{},
      "ailments":{}
     },
     "outturn":{
       "userid":"91",
       "username":"james",
       "items":{},
       "ailments":{}
      }

However, the keys are output without the quotes which will later result into errors when reading the JSON file back. Why is that? How can I customize it so it looks like my expected output?

halfer
  • 19,824
  • 17
  • 99
  • 186
Cain Nuke
  • 2,843
  • 5
  • 42
  • 65
  • 2
    Why not just `JSON.stringify()` and dump the string into a file? A quick search for "writing JSON to file in node.js" should turn up plenty of results. – Robby Cornelissen Feb 09 '23 at 01:05
  • Have you checked the documentation? [Setting `compact` to false or an integer creates more reader friendly output.](https://nodejs.org/api/util.html#utilinspectobject-options) – Christopher Feb 09 '23 at 01:15
  • JSON.stringify throws circularity errors. thats why Im trying other alternatives. – Cain Nuke Feb 09 '23 at 01:17
  • I tried compact to false but I still get no quotes wrapped around keys. – Cain Nuke Feb 09 '23 at 01:23
  • 3
    `util.inspect` doesn't output JSON. Options were given in [the original question](https://stackoverflow.com/questions/75390390/writefilesync-not-writing-all-variables-to-a-json-file). I suspect the answer is just use [flatted](https://github.com/WebReflection/flatted) – Matt Feb 09 '23 at 10:54
  • so there is no way to do this with util.inspect? – Cain Nuke Feb 09 '23 at 19:03
  • No, there's not. It's the wrong tool for the job. – Bergi Mar 09 '23 at 02:39

0 Answers0