【问题标题】:Parsing a returned JSON in Python and checking if values exist [duplicate]在 Python 中解析返回的 JSON 并检查值是否存在 [重复]
【发布时间】:2023-01-24 23:30:53
【问题描述】:

我正在从一个在线站点获取一些 JSON 数据并具有以下内容:-

try:
    data = response.read()  
    json_response = json.loads(source)
    name = json_response['profiles'][0]['content']['nameFull']
    first_name = json_response['profiles'][0]['content']['name']['first']
    surname = json_response['profiles'][0]['content']['name']['last']
    employment_type = json_response['profiles'][0]['content']['employeeType']['title']
except:
    continue

对于上面分配的每个变量,我然后对每个变量执行一个操作。这很好用如果JSON 中的所有值都存在,但如果例如“标题”条目不存在,则此操作失败。如果不希望在每个变量上添加“try/except”,我该如何处理这个问题?有没有更 Pythonesque 的方式来处理这个?同样,如果默认值不存在于顶层而不是每个 JSON 条目级别,有没有办法添加默认值?

谢谢

【问题讨论】:

    标签: python json python-3.x


    【解决方案1】:

    不确定这是否有帮助,但这是我发现的:

    1. 使用 get() 方法:get() 方法允许您指定一个默认值,如果您尝试访问的键在 JSON 中不存在,则返回该默认值。这可能是比使用多个 try-except 块更优雅的解决方案,因为您可以在一行代码中为每个键指定默认值。例子:

      name = json_response.get('profiles')[0].get('content').get('nameFull', 'N/A')

      1. 使用 dict.setdefault() 方法:setdefault() 方法允许您为不存在的键设置默认值。仅当键不存在时,此方法才会将键值对添加到字典中。例子:

        json_response['profiles'][0]['content'].setdefault('employeeType', {}).setdefault('title', 'N/A')

      2. 使用递归:使用递归遍历json数据,访问前检查每个key是否存在。如果您需要处理 JSON 中多个级别的缺失数据,这会很有用。

      def get_json_value(json_data, keys, default=None):
          if keys and json_data:
              key = keys.pop(0)
              if key in json_data:
                  return get_json_value(json_data[key], keys, default)
          return json_data or default
      
      name = get_json_value(json_response, ['profiles', 0, 'content', 'nameFull'], 'N/A')
      

      4.使用 pandas 库中的 json_normalize 来展平 json 并使用 fillna 方法为缺失字段设置默认值。

      import pandas as pd
      
      json_df = pd.json_normalize(json_response)
      json_df.fillna('N/A', inplace=True)
      

    【讨论】:

      猜你喜欢
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      相关资源
      最近更新 更多