无法在JSON上读取多个级别

时间:2019-02-08 00:40:03

标签: node.js json

所以我做了这个JSON文件...

{ 'Blue Aces Bakery':
{ Symbol: 'BAB',
 Stock:
  { onSale: {},
    Shares: 13,
    Price: 10,
    marketCap: 130,
    Balance: 10075,
    stockOpen: 10,
    previousClose: 10,
    chartFile: './public/BAB',
    Intraday: [Array],
    previousIntraday: [Array] 
    } 
    } 
}

但是当我运行这段代码

var stockData = require('./stocks.json');
console.log(stockData[Companies])
if(stockData[Companies].Stock.onSale.Bids) {...

我明白了:

{ 'Blue Aces Bakery':
{ Symbol: 'BAB',
 Stock:
  { onSale: {},
    Shares: 13,
    Price: 10,
    marketCap: 130,
    Balance: 10075,
    stockOpen: 10,
    previousClose: 10,
    chartFile: './public/BAB',
    Intraday: [Array],
    previousIntraday: [Array] } } }

  (node:14680) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'onSale' of undefined
at checkStocks (C:\Users\Mark\Desktop\Stock Bot\base.js:30:39)

这对我来说毫无意义。有人可以帮我解决我在这里做错的事情吗?我已经尝试过查找它,而且似乎没有其他人遇到相同的问题。

1 个答案:

答案 0 :(得分:0)

console.log()仅显示了几层深层物体。

您将要使用console.dir()(取决于版本等)或util.inspect()

演示:

$ node 
> let a = {}; a.b = {}; a.b.c = {}; a.b.c.d = {}; a.b.c.d.e = [0,1,2,3,4];
[ 0, 1, 2, 3, 4 ]
> console.log(a)
{ b: { c: { d: [Object] } } }
undefined
> console.dir(a)
{ b: { c: { d: [Object] } } }
undefined
> console.log(util.inspect(a, false, null, true))
{ b: { c: { d: { e: [ 0, 1, 2, 3, 4 ] } } } }
undefined
> process.version
'v10.14.1'
>