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 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?