Home > Software design >  How do I access JSON keys with same names from objects with different names?
How do I access JSON keys with same names from objects with different names?

Time:10-21

I have a list of objects like this:

{
  "311243752289206293": {
    "user_id": "311243752289206293",
    "username": "Daniel",
  },
  "766430137381683201": {
    "user_id": "766430137381683201",
    "username": "Jeff",
  },
  "890423576283463690": {
    "user_id": "890423576283463690",
    "username": "Larry",
  },

How can I access all the user IDs if the object names differ? Is there any way to refer to all objects despite the various names?

I'd like to put these IDs in a list like this:

import json

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

id_list = []
id_list.append(data['user_id']) # <--- What do I do here to access all the user_id keys from the objects with different names?

Thanks beforehand.

CodePudding user response:

You don't have a list of objects you have a dictionary.

Built-in dict class has method returning keys, values or both (items).

All you need to do is to iterate over the values and get user_id from each object:

id_list = [user["user_id"] for user in data.values()]
  • Related