代码之家  ›  专栏  ›  技术社区  ›  MyPan

从json格式提取项目

  •  1
  • MyPan  · 技术社区  · 4 年前

    我试图从json格式中提取数据,该格式还包含DICT列表。但当我访问它时,它就会显示出来 None .

    我想做的是:-

    我正在努力 content 从下面的这个反应

    密码py

    def extract():
        res = {
          "$schema": "http://json-schema.org/schema#",
          "anyOf": [{
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "response": {
                    "type": "integer"
                  },
                  "content": {
                    "type": "array",
                    "items": {
                      "type": "object",
                      "properties": {
                        "id": {
                          "type": "integer"
                        },
                        "title": {
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "title"
                      ]
                    }
                  }
                },
                "required": [
                  "content",
                  "response"
                ]
              }
            }
          ]
        }
    
        # When I try this then it shows an error
        json_ext = json.loads(res)
        print(json_ext['anyOf[0].properties'])
    

    它返回为错误

    TypeError:JSON对象必须是str、bytes或bytearray,而不是dict

    我也尝试过使用

    def deep_get_imps(data, key: str):
        split_keys = re.split("[\\[\\]]", key)
        out_data = data
        for split_key in split_keys:
            if split_key == "":
                return out_data
            elif isinstance(out_data, dict):
                out_data = out_data.get(split_key)
            elif isinstance(out_data, list):
                try:
                    sub = int(split_key)
                except ValueError:
                    return None
                else:
                    length = len(out_data)
                    out_data = out_data[sub] if -length <= sub < length else None
            else:
                return None
        return out_data
    
    
    def deep_get(dictionary, keys):
        return reduce(deep_get_imps, keys.split("."), dictionary)
    

    print(deep_get(res, "anyOf[0].items[0]"))
    

    但它没有返回任何结果,它仍然没有得到响应 所容纳之物 回答

    我已经做了很多次了,但它仍然不起作用。任何帮助都将不胜感激。提前谢谢你。

    1 回复  |  直到 4 年前
        1
  •  1
  •   Patrick Klein    4 年前

    你的目标, res ,是一个所谓的dict,这就是为什么你的代码会抛出 TypeError 当你打电话的时候 json_ext = json.loads(res) 自从 loads 仅适用于字符串和类似类型。
    你可能更想做的是:

    def extract():
        res = {
              ...  # shortened for readability
        }
        print(res["anyOf"][0]["items"]["properties"]["content"])