仅打印json fi的特定部分

2024-06-17 12:24:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道在python中打印下面代码的name的数据时我做错了什么。你知道吗

        import urllib.request, json 
    with urllib.request.urlopen("<THIS IS A URL IN THE ORIGINAL SCRIPT>") as url:
        data = json.loads(url.read().decode())
    print (data['Departure']['Product']['name'])
print (data['Departure']['Stops']['Stop'][0]['depTime'])

这是我从中获取数据的api:

    {
  "Departure" : [ {
    "Product" : {
      "name" : "Länstrafik - Buss 201",
      "num" : "201",
      "catCode" : "7",
      "catOutS" : "BLT",
      "catOutL" : "Länstrafik - Buss",
      "operatorCode" : "254",
      "operator" : "JLT",
      "operatorUrl" : "http://www.jlt.se"
    },
    "Stops" : {
      "Stop" : [ {
        "name" : "Gislaved Lundåkerskolan",
        "id" : "740040260",
        "extId" : "740040260",
        "routeIdx" : 12,
        "lon" : 13.530096,
        "lat" : 57.298178,
        "depTime" : "20:55:00",
        "depDate" : "2019-03-05"
      }

Tags: 代码namejsonurldatarequesturllibproduct
3条回答

你把词典的样本写得乱七八糟。以下是我的看法:

d =     {
  "Departure" : [ {
    "Product" : {
      "name" : "Länstrafik - Buss 201",
      "num" : "201",
      "catCode" : "7",
      "catOutS" : "BLT",
      "catOutL" : "Länstrafik - Buss",
      "operatorCode" : "254",
      "operator" : "JLT",
      "operatorUrl" : "http://www.jlt.se"
    },
    "Stops" : {
      "Stop" : [ {
        "name" : "Gislaved Lundåkerskolan",
        "id" : "740040260",
        "extId" : "740040260",
        "routeIdx" : 12,
        "lon" : 13.530096,
        "lat" : 57.298178,
        "depTime" : "20:55:00",
        "depDate" : "2019-03-05"
      }]}}]}

下面是如何打印depTime

print(d["Departure"][0]["Stops"]["Stop"][0]["depTime"])

你错过的重要部分是d["Departure"][0],因为d["Departure"]list。你知道吗

正如凯尔在前面的回答中所说,data["Departure"]是一个列表,但你试图把它当作字典。有两种可能的解决方案。你知道吗

  1. data["Departure"]["Stops"]["Stop"]等更改为data["Departure"][0]["Stops"]["Stop"]等。

  2. 将JSON文件更改为dictionary,这样可以保留原始代码。这将使最终的JSON片段看起来像这样:

"Departure" : {
  "Product" : {
    "name" : "Länstrafik - Buss 201",
    "num" : "201",
    "catCode" : "7",
    "catOutS" : "BLT",
    "catOutL" : "Länstrafik - Buss",
    "operatorCode" : "254",
    "operator" : "JLT",
    "operatorUrl" : "http://www.jlt.se"
  },
  "Stops" : {
    "name" : "Gislaved Lundåkerskolan",
    "id" : "740040260",
    "extId" : "740040260",
    "routeIdx" : 12,
    "lon" : 13.530096,
    "lat" : 57.298178,
    "depTime" : "20:55:00",
    "depDate" : "2019-03-05"
  }
}

data["Departure"]是一个列表,你把它作为字典索引。你知道吗

相关问题 更多 >