0

I have this object in a .js file being run with NodeJS on the command line. I am trying to save the "print-friendly" version of it to a variable, and then to write the variable to a file:

var obj = {}

obj['keys'] = ['a', 'b', 'c', 'd',]
obj['animals'] = [
    {name: 'giraffe'}, 
    {name: 'zebra'}, 
    {name: 'bird'}, 
    ]
    
obj['arrs'] = {
    'sky': {color: 'blue'},
    'grass': {color: 'green'},
    'brick': {color: 'brown'},
}

obj['arrs_2'] = []
obj['arrs_2']['sky'] = {color: 'blue'}
obj['arrs_2']['grass'] = {color: 'green'}
obj['arrs_2']['brick'] = {color: 'brown'}

When I use console.log(obj), I get:

{
  keys: [ 'a', 'b', 'c', 'd' ],
  animals: [ { name: 'giraffe' }, { name: 'zebra' }, { name: 'bird' } ],
  arrs: {
    sky: { color: 'blue' },
    grass: { color: 'green' },
    brick: { color: 'brown' }
  },
  arrs_2: [
    sky: { color: 'blue' },
    grass: { color: 'green' },
    brick: { color: 'brown' }
  ]
}

Everything prints out correctly. But if I try to console.log(JSON.stringify(obj, null, 4)), I get:

{
    "keys": [
        "a",
        "b",
        "c",
        "d"
    ],
    "animals": [
        {
            "name": "giraffe"
        },
        {
            "name": "zebra"
        },
        {
            "name": "bird"
        }
    ],
    "arrs": {
        "sky": {
            "color": "blue"
        },
        "grass": {
            "color": "green"
        },
        "brick": {
            "color": "brown"
        }
    },
    "arrs_2": []
}

I was trying:

var out = JSON.stringify(obj, null, 4)
fs.writeFileSync('out.txt', out, (err) => {
    if (err) {
        throw err;
    }}
)

to write it, but the JSON.stringify() is unable to print the contents of arrs_2 (and displays no errors). Is there a way to capture the console.log() output to a variable without actually printing it to the screen? Or maybe a different function than JSON.stringify() that can convert the full object into a string like console.log() can?

2
  • 2
    obj['arrs_2'] = [] 👈 you've initialised arrs_2 as an array but you then add named object properties. These won't serialize to JSON because you told it that it's an array, not an object Commented Nov 11, 2024 at 3:17
  • It looks like the answer is here: stackoverflow.com/a/24728537/1827764 Commented Nov 11, 2024 at 4:19

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.