【问题标题】:Trying to access JSON data through an API尝试通过 API 访问 JSON 数据
【发布时间】:2018-12-31 05:02:32
【问题描述】:

我正在使用节点请求来访问 api 上的数据。现在,当我使用以下代码访问正文时,我得到以下响应。

app.post("/", function(req, res){

//var series = req.body.series;
var circuits = req.body.Circuits;
var url = req.body.url

request("http://ergast.com/api/f1/circuits/" + circuits + ".json", function(error, response, body){
    console.log(body);
    res.write("<p>Here is the information about the circuit " + circuits + " in the " + url + " is about the circuit </p>")
  });
})

我从 Api 得到以下响应。

{
"MRData": {
    "xmlns": "http://ergast.com/mrd/1.4",
    "series": "f1",
    "url": "http://ergast.com/api/f1/circuits/brands_hatch.json",
    "limit": "30",
    "offset": "0",
    "total": "1",
    "CircuitTable": {
        "circuitId": "brands_hatch",
        "Circuits": [
            {
                "circuitId": "brands_hatch",
                "url": "http://en.wikipedia.org/wiki/Brands_Hatch",
                "circuitName": "Brands Hatch",
                "Location": {
                    "lat": "51.3569",
                    "long": "0.263056",
                    "locality": "Kent",
                    "country": "UK"
                }
            }
        ]
    }
  }
}

现在的问题是我需要访问这些属性。例如,url 在段落标签中给了我一个未定义的错误。 任何帮助将不胜感激。

【问题讨论】:

  • body.MRData.url 不起作用?
  • @Pedro Silva 那行不通。它仍然给我未定义!
  • 检查typeof body,如console.log(typeof body),如果是字符串,你应该使用JSON.parse(body).MRData.url,如果不是我真的无法理解你的问题.
  • 我正在尝试访问 url 或 Circuits:[] 中的任何属性。这是我得到的回应。 TypeError: Cannot read property 'CircuitTable' of undefined

标签: node.js api npm request


【解决方案1】:

在你的 console.log 中应该是

console.log(JSON.parse(body)); 

或者

var bodyParsed = JSON.parse(body);
var yourUrl = bodyParsed.MRData.url

正如我在cmets中所说,你的body是一个字符串,console.log(typeof body)返回的是字符串,所以需要解析成一个有属性的对象。

【讨论】:

  • 假设我想访问这部分json数据中的url"Circuits": [ { "circuitId": "brands_hatch", "url": "http://en.wikipedia.org/wiki/Brands_Hatch", "circuitName": "Brands Hatch", "Location": { "lat": "51.3569", "long": "0.263056", "locality": "Kent", "country": "UK" }
  • bodyParsed.MRData.CircuitTable 应该按照您的要求工作。
  • var request = require('request'); request('ergast.com/api/f1/circuits/brands_hatch.json', function (error, response, body) { var bodyParsed = JSON.parse(body) console.log(bodyParsed.MRData.CircuitTable); });那是我的代码,它就像一个魅力,我不明白它怎么不能和你一起工作。
  • 这是我用段落标签得到的信息 这是关于 [object Object] 系列中的电路 aintree 的信息。 res.write("&lt;p&gt;Here is the information about the circuit " + circuits + " in the " + yourUrl + " series &lt;/p&gt;")
  • 您必须在 res.write 上执行 JSON.stringify(bodyParsed.MRData.CircuitTable)。否则,无法从对象转换为字符串。
猜你喜欢
  • 2021-12-31
  • 2020-02-24
  • 2014-11-24
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多