【问题标题】:Can't access key in json file [duplicate]无法访问 json 文件中的密钥 [重复]
【发布时间】:2017-01-19 18:17:10
【问题描述】:

我尝试使用 python 处理这个 JSON 文件: JSON file

我想用这个代码访问'lignes' 键:

import json

with open('arrets-reseau-irigo.json') as data_file:
    data = json.load(data_file)

    for i in data:
        print("datasetid is {0}".format(i['datasetid']))
        print("nom arret is {0}".format(i['fields']['nom_arret']))
        print("coordonnées is {0}".format(i['fields']['geo_point_2d']))
        try :
            if format(i['fields']['lignes']) in data :
                print("Fields : is {0}".format(i['fields']['lignes']))
            else :
                print('nothing')
        except:
            print("EXCEPTION")

结果是:

datasetid is arrets-reseau-irigo
nom arret is GIRARD
coordonnées is [47.4909169756, -0.581150255698]
nothing
datasetid is arrets-reseau-irigo
nom arret is HOTEL DE VILLE TRAM B/C
coordonnées is [47.4716862858, -0.546754596835]
EXCEPTION

您是否有示例代码来解决我的问题并仅在 'ligne' 键存在时显示值?

【问题讨论】:

  • 你能告诉我们你的 json 文件长什么样吗?
  • 我在那个 JSON 文件中看不到任何“线条”
  • 我修改了链接,错了对不起^^

标签: python json


【解决方案1】:

使用您提供的文件示例。

[
  {
    "datasetid": "arrets-reseau-irigo",
    "fields": {
      "accessib": "O",
      "date_maj": "Décembre 2016",
      "geo_point_2d": [
        47.4682358304,
        -0.550894481011
      ],
      "lignes": "L_1,L_1D,L_1S,L_2,L_2D,L_2S,L_3,L_3D,L_3S,L_4,L_6,L_10",
      "nom_arret": "FOCH - SAINT AUBIN",
      "source": "KEOLIS Réseau IRIGO"
    },
    "geometry": {
      "coordinates": [
        -0.550894481011,
        47.4682358304
      ],
      "type": "Point"
    },
    "record_timestamp": "2017-01-12T17:05:52+01:00",
    "recordid": "65e54c3d5e87a803c3a2199fbde5596e5833be8f"
  },
 ]

更新:

import json

with open('file.json') as data_file:
    data = json.load(data_file)

for i in data:
    print("datasetid is {0}".format(i['datasetid']))
    print("nom arret is {0}".format(i['fields']['nom_arret']))
    print("coordonnées is {0}".format(i['fields']['geo_point_2d']))
    description = i['fields'].get('lignes', 'nothing')
    print(description)

【讨论】:

  • 嗨@Taras,我的文件错误^^我修改了链接。你可以检查一下:)
  • 我想用这个代码访问 'lignes' 键
  • 我已经更新了答案。
  • 那行得通 ^^ 但为什么它不适用于我的代码? 'get' 的规则是什么?
【解决方案2】:

如果我理解正确,而不是尝试/除了你想做的事

if 'lignes' in i['fields']:
    print("Fields : is {0}".format(i['fields']['lignes']))
else :
    print('nothing')      

【讨论】:

  • 我尝试了你的代码,但它总是显示“什么都没有”:/
  • 我已更新答案以删除附加检查 if format(i['fields']['lignes']) in data :
【解决方案3】:

您发布的示例 JSON 文件中不存在 lingnes 键,但它与“格式”处于同一级别。像这样的

for count in data:
    if 'fields' in data[count]:
        print(data[count]['fields']['format'])

【讨论】:

    【解决方案4】:

    要检查字典中是否存在键,请执行
    if key in dict: ... 所以,就你而言,
    if 'lignes' in i['fields']: ...

    目前,您正在检查 i['fields']['lignes']value 是否是 datakey,这没有意义,也可能会抛出在整行甚至完成评估之前出现异常,即在评估i['fields']['lignes'] 时可能会出错,因为您尚未检查'lignes' 是否是i['fields'] 的键。

    【讨论】: