Home > OS >  Extract items from json format
Extract items from json format

Time:04-16

I am trying to extract data from json format, which also contains list of dicts. But when I access it then it shows None.

What I am trying to do:-

I am trying to get content from this below resonse

code.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'])

It returns as error

TypeError: the JSON object must be str, bytes or bytearray, not dict

I have also tried using

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)

AS

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

But it returns none, It is still not getting content response.

I have many times but it is still not working. Any help would be much Appreciated. Thank You in Advance.

CodePudding user response:

Your object, res, is a so called dict and that's why your code throws the TypeError when you call json_ext = json.loads(res), since loads only works on strings of characters and similar types.
What you probably wanted to do is more like this:

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