Home > Blockchain >  How do I access JSON elements and put the contents into lists?
How do I access JSON elements and put the contents into lists?

Time:11-27

I have a JSON list of objects like this:

"server-1": {
    "username": "admin542",
    "on_break": false,
    "scheduling_type": 1,
    "schedule": {
      "Monday": [
        "11:00"
      ],
      "Tuesday": [
        "12:00",
        "13:00"
      ],
    },
    "com_type": 2
  },
  "server-2": {
    "username": "admin543",
    "on_break": false,
    "scheduling_type": 2,
    "schedule": {
      "Monday": [
        "10:00"
      ],
      "Wednesday": [
        "13:00",
        "14:00"
      ]
    },
    "com_type": 2
  },

I want to access the schedule for a specific server and put it into lists. Let's say I want to access the schedule for server-2. How can I access it and put it in a list like this?

schedule_days = ["Monday", "Wednesday"]
schedule_times = [["10:00"], ["13:00", "14:00"]]

I tried with:

import json

with open("systemfile.json", "r") as f:
    data = json.load(f)

schedule_days = []
schedule_days.append(data[str("server-2")]["schedule"])

### Which gave me

[{'Monday': ['11:00'], 'Wednesday': ['13:00', '14:00']}]

Is there any way I can access that to make a list like the example above? Or what would you do?

Thanks beforehand.

CodePudding user response:

data['server-2']['schedule'] is the sub-dictionary you want to access. You can use the .keys() method of this dictionary to get the keys, and the .values() method to get the values.

schedule_days = list(data['server-2']['schedule'].keys())
schedule_times = list(data['server-2']['schedule'].values())
  • Related