为什么console.log解析后不显示各级JSON?

问题描述 投票:0回答:2

我正在练习简单的 API。我从 OXFORD API 请求数据。数据被正确接收,我可以浏览它并提取我想要的定义或词源。但是,当我在 .json() 之后打印完整响应时,某些数组的内容显示为 [Array]。知道我缺少什么吗?

我的代码如下所示:

let endpoint = "https://od-api.oxforddictionaries.com/api/v2/entries/en-gb/ace?fields=definitions&strictMatch=false";
const   headers: {
    'app_id': app_id,
    'app_key': app_key
  }

fetch(endpoint,  {headers} )            
.then(rawResponse=>rawResponse.json())
.then(response=>{
    console.log(response);
    console.log(response.results[0].lexicalEntries[0].entries[0].etymologies[0])
    });

控制台中的结果如下所示: '''

{
  id: 'ace',
  metadata: {
    operation: 'retrieve',
    provider: 'Oxford University Press',
    schema: 'RetrieveEntry'
  },
  results: [
    {
      id: 'ace',
      language: 'en-gb',
      lexicalEntries: [Array],
      type: 'headword',
      word: 'ace'
    },
    {
      id: 'ace',
      language: 'en-gb',
      lexicalEntries: [Array],
      type: 'headword',
      word: 'ace'
    }
  ],
  word: 'ace'
}
Middle English (denoting the ‘one’ on dice): via Old French from Latin as ‘unity, a unit’

''' 我尝试过 Apps 脚本,得到了相同的结果 '''

 results: 
   [ { id: 'ace',
       language: 'en-gb',
       lexicalEntries: [Object],
       type: 'headword',
       word: 'ace' },

'''

提前致谢

json parsing console.log stringify
2个回答
0
投票

这里的第一条评论激发了我的答案和进一步的搜索。 console.log() 主要打印字符串,当向其传递数组或对象时,它会尽可能地解释它们。因此,对于第一级

[object, object]
{A:[],B:[]}
,它可以毫无问题地打印它。 当我们深入研究从 API 响应解析的 JavaScript 对象中的更多嵌套数组和对象时,它将无法正确解释它并返回 [object] 或 [Array] 例如通过console.log可以轻松打印以下内容

console.log([{A:1},{B:2},{C:3}])

并返回

[ { A: 1 }, { B: 2 }, { C: 3 } ]

还有,

console.log([{A:1},{B:2},{C:3,D:[1,2,3]}]) 

轻松打印

[ { A: 1 }, { B: 2 }, { C: 3, D: [ 1, 2, 3 ] } ]

但是,

 console.log([{A:1},{B:2},{C:3,D:[{E:1},{F:2},{G:3}]}])

退货

[ { A: 1 },
  { B: 2 },
  { C: 3, D: [ [Object], [Object], [Object] ] } ]

所以我们需要,使用

JSON.stingify
将其转换为字符串

console.log(JSON.stringify([{A:1},{B:2},{C:3,D:[{E:1},{F:2},{G:3}]}]))

成功返回

[{"A":1},{"B":2},{"C":3,"D":[{"E":1},{"F":2},{"G":3}]}]

但是,当 JSON 对象更大更深时,您可能需要使用

来美化它
console.log(JSON.stringify([{A:1},{B:2},{C:3,D:[{E:1},{F:2},{G:3}]}],null,2))

它回来了

[
  {
    "A": 1
  },
  {
    "B": 2
  },
  {
    "C": 3,
    "D": [
      {
        "E": 1
      },
      {
        "F": 2
      },
      {
        "G": 3
      }
    ]
  }
]

您可以在 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

中找到参考

0
投票

如果您在使用express.js时触发该问题,则说明express无法读取json值。你必须使用中间件

app.use(express.json())

这将有助于表达理解 json 值

© www.soinside.com 2019 - 2024. All rights reserved.