Access list names in JSON file

Question:

I have a JSON dataset with scheduling information.

{
  "admin-1": {
    "username": "user0",
    "current_amount_of_patients": 0,
    "on_break": false,
    "scheduling_type": 2,
    "schedule": {
      "Monday": [
        "17:00:00"
      ],
      "Tuesday": [
        "17:00:00",
        "18:00:00"
      ],
      "Wednesday": [
        "10:00:00",
        "11:00:00",
        "12:00:00",
        "13:00:00"
      ]
    },
    "com_type": 1
  },
  "admin-2": {
    "username": "user1",
    "on_break": false,
    "scheduling_type": 1,
    "timezone": "America/Los_Angeles",
    "schedule": {
      "Tuesday": [
        "17:00:00",
        "18:00:00"
      ],
      "Wednesday": [
        "10:00:00",
        "11:00:00",
        "12:00:00",
        "13:00:00"
      ],
      "Sunday": [
        "09:00:00",
        "10:00:00",
        "11:00:00",
        "12:00:00"
      ]
    },
    "com_type": 2
  }
}

I’d like to access only the names of the days and put them in lists for every user. Meaning, the output would be:

days = [['Monday', 'Tuesday', 'Wednesday'], ['Tuesday', 'Wednesday', 'Sunday']]

I tried doing it this way:

days = [user["schedule"].keys() for user in data.values()]

But it didn’t give any output. Note that I’m doing it in a for loop in case I’ll add more users to the database.

Do you have any ideas of how to make it work to the desired output?

Asked By: Eliahs Johansson

||

Answers:

Try (your_data.json file contains the Json from your question):

import json

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

days = [list(d["schedule"] or []) for d in data.values()]
print(days)

Prints:

[['Monday', 'Tuesday', 'Wednesday'], ['Tuesday', 'Wednesday', 'Sunday']]
Answered By: Andrej Kesely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.