【问题标题】:Read the property of Object through Javascript通过Javascript读取Object的属性
【发布时间】:2021-08-02 09:52:35
【问题描述】:

我正在尝试从对象文本中提取价格值。我收到未定义的值。请有任何建议。

const fetch = require('node-fetch');

console.log('1. lets start')
fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
    .then(res => res.text())
    .then(text => {
     
      console.log(text['price']);



    })

【问题讨论】:

  • text 是一个字符串,而不是一个对象。它没有 .price 属性。
  • 如果您要获取的数据是 JSON,则使用 res.json() 代替 res.text() 然后您将获得一个对象,但前提是您要获取的数据实际上是 JSON 到从...开始。只有在您发送console.log(text) 并向我们展示数据的实际情况时,人们才能真正为您提供帮助。

标签: javascript node.js arrays object


【解决方案1】:

您引用的网址返回 json,而不是文本,正如其他答案所建议的那样。

除此之外,您可以使用更好的语法 text.price 而不是 text['price']

const fetch = require('node-fetch');

console.log('1. lets start')
fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
    .then(res => res.json())
    .then(text => {
      console.log(text.price);
    })

【讨论】:

    【解决方案2】:

    应该是 res.json() 而不是 text()

    const fetch = require('node-fetch');
    
    console.log('1. lets start')
    fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
        .then(res => res.json())
        .then(text => {
          console.log(text['price']);
        })
    

    【讨论】:

      【解决方案3】:

      将text()改为json(),以获取json对象:

      const fetch = require('node-fetch');
      
      console.log('1. lets start')
      fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
          .then(res => res.json())
          .then(res => {
            console.log(res['price']);
          })
      

      【讨论】:

        【解决方案4】:

        您可能正在寻找 JSON.parse()。例如:

        fetch('https://api.binance.us/api/v3/avgPrice?symbol=DOGEUSD')
            .then(res => res.text())
            .then(text => {
              const myObject = JSON.parse(text);
              console.log(myObject['price']);
            })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-17
          • 2019-07-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-05
          • 1970-01-01
          相关资源
          最近更新 更多