-1

here is my json:

[
    {
        "customer": "BigCo",
        "performances": [
            {
                "playID": "hamlet",
                "audience": 55
            },
            {
                "playID": "as-like",
                "audience": 35
            },
            {
                "playID": "othello",
                "audience": 40
            }
        ]
    }
]

here is my code(environment is node.js):

let readFile = require('fs').readFileSync

let invoices = JSON.parse(readFile('./invoices.json', 'utf8'))

console.log(invoices);

here is my result:

[
  { customer: 'BigCo', performances: [ [Object], [Object], [Object] ] }
]

I have read some questions related, and get some solutions like invoices = invoices[0] or JSON.parse(JSON.stringify()). The thing I really hope to know is the reason. Why do I get the result [ [Object], [Object], [Object] ] and Which part cause the problem?

youfu
  • 11
  • 2
  • 1
    NodeJS only shows the contents of objects for two "levels" deeps. Log `console.log(invoices.performances[0])` instead to see the contents of your array. More info can be found here: https://nodejs.dev/learn/how-to-log-an-object-in-nodejs – Nick Parsons Mar 06 '22 at 07:33
  • 1
    thanks, the answer has completely solved my problem. That is what I looking for – youfu Mar 06 '22 at 17:08

2 Answers2

-1

I am no expert but the reason for this is that they are nested objects.

-1

You need to first convert the contents of the file into string and then parse it to JSON.

Use the following code :

let readFile = require('fs').readFileSync

let invoices = JSON.parse(readFile('./invoices.json', 'utf8').toString())

console.log(invoices[0]);

the output would be :

{
  customer: 'BigCo',
  performances: [
    { playID: 'hamlet', audience: 55 },
    { playID: 'as-like', audience: 35 },
    { playID: 'othello', audience: 40 }
  ]
}
Dharman
  • 30,962
  • 25
  • 85
  • 135