0

below is how the list looks like. I want to access list of list. I want to access it because I want to store it to a database.the response_body looks like this.

[
  {
    "username_count": 0,
    "description": "som string",
    "rules": [
      {
        "id": 10845,
        "type": "some string"
      }
    ],
    "event_count": 7,
    "flow_count": 0,
    "assigned_to": null,
    "security_category_count": 3,
    "follow_up": false,
    "source_address_ids": [
      858,345
    ],
    "source_count": 1,
    "inactive": false,
    "protected": false,
    "category_count": 3,
    "source_network": "some string",
    "destination_networks": [
      "other",
      "some string"
    ],
    "closing_user": null,
    "close_time": null,
    "remote_destination_count": 1,
    "start_time": 1563267761163,
    "last_updated_time": 1563268006582,
    "credibility": 3,
    "magnitude": 6,
    "id": 4786,
    "categories": [
      "string1",
      "string2",
      "string3"
    ],
    "severity": 8,
    "policy_category_count": 0,
    "device_count": 3,
    "closing_reason_id": null,
    "offense_type": 0,
    "relevance": 5,
    "domain_id": 0,
    "offense_source": "172.168.15.120",
    "local_destination_address_ids": [
      3
    ],
    "local_destination_count": 1,
    "status": "OPEN"
  },

I have tried doing this

 response_body = json.loads(response.read().decode('utf-8'))


    for j in response_body:
        obj, created = Offenses.objects.get_or_create(oid=j['id'], defaults={'description': j['description'], 'assigned_to': j['assigned_to'], 'categories':j['categories']})

but this doesn't work as it returns None

how should I access the category in the above list because category is itself a list? it should return some string but instead returns None.

  • 3
    What happens if you try `response.content.decode('utf-8')` instead of `read()`? If you are using `requests` lib for fetching the response, you can simply use `response.json()`, see https://2.python-requests.org//en/latest/user/quickstart/#json-response-content – Risadinha Jul 16 '19 at 09:33
  • See also https://stackoverflow.com/questions/16877422/whats-the-best-way-to-parse-a-json-response-from-the-requests-library – Risadinha Jul 16 '19 at 09:37
  • You are asking 2 questions. Please decide for 1 question at a time, ask the other question separately. – Risadinha Jul 16 '19 at 09:39
  • `"categories": [ "string1", "string2", "string3" ],` I just want to access this categories attribute inside of this huge list of lists..so how should i access it – Hassan Ikram Jul 16 '19 at 10:03
  • using the above methods u mentioned did not help. response is already decoded to response_body and now i just want to access the lists that are inside of these huge lists and save it in my database field – Hassan Ikram Jul 16 '19 at 10:06
  • if you are using PostgreSQL, it provides ArrayField – Vaibhav Vishal Jul 16 '19 at 10:29
  • I am using MySQL – Hassan Ikram Jul 16 '19 at 11:11

0 Answers0