-1

I have a JSON file which is a tuple of multiple dictionaries and I want to extract keys and values from some of them.

The file looks something like this (this is just an example of the structure with random keys and values):

file = 
[
    {
        "element": {
            "name": "Ana",
            "bio": "xx",
            "type": "female"
        },
        "ID": "1234",
        "status": "STOPPED"
    },
    {
         "element": {
            "name": "Bob",
            "bio": "xy",
            "type": "male"
        },
        "ID": "5678",
        "status": "STOPPED"
    },
    {
         "element": {
            "name": "Chloe",
            "bio": "xx",
            "type": "female"
        },
        "ID": "8912",
        "status": "STOPPED"
      }
]

What I want to extract all names (Ana, Bob, Chloe) and their ids something like this:

Ana = 1234,
Bob = 5678

etc.

Whatever that I have already tried gives back attribute errors etc. I am not even sure how to iterate through this correctly so that it takes name and ID because they don't have the same location (the name is inside element dict).

I even tried converting the file to list.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Susomejak
  • 3
  • 3
  • 1
    Okay, so we can assume that, after you have done all the JSON loading stuff, you have a variable `file` in your program, which has the same value as if you had run the Python code above? Did you verify that? If you don't have such a result, then you need to make sure you understand how to parse the JSON data. If you do, then you work with it *exactly the same way you would if it had come from anywhere else*. For example: at the top level, it's a list, right? *How do you get the first element of a list?* When you have that element, according to its structure, how would you get the name and ID? – Karl Knechtel Jan 19 '22 at 11:57
  • "Whatever that I have already tried gives back attribute errors etc." We can only tell you what is wrong with code that you actually show to us, and we can only explain error messages that we can actually see for ourselves. – Karl Knechtel Jan 19 '22 at 11:58
  • Thanks for reply. I have json file and I used open(file.json) as file and in read mode (so 'r') and converted it to list. so lets say: lst = list(file) after that i wanted to try with get so: list_element = lst.get('element'), that is where i get error. ``` with open('file.json', 'r') as file: lst = list(file) element = lst.get('element') id = lst.get('ID') for i in range (len(element)): name = element[0].get('ID') ``` – Susomejak Jan 19 '22 at 12:01
  • That **does not parse the JSON data**. When you read the file, you just get a string, and the `{` and `[` etc. symbols in it have *no special meaning*. Converting it to list just means that *each symbol becomes an element of the list*. You should *use a search engine* in order to learn how to parse JSON. – Karl Knechtel Jan 19 '22 at 12:03
  • I know how that loads exists... But I am not sure how to correctly use it since it is dictionary inside of dictionary. That is why I asked question here, to find out the answer and learn it. Since I failed to find it on search engine you mentioned .However I appreciate your effort and taking time to answer and point out the mistake I made thinking that loads will have to be used differently here. Thanks! – Susomejak Jan 19 '22 at 12:38
  • "But I am not sure how to correctly use it since it is dictionary inside of dictionary." No, it isn't. It is a **string**. You use `loads` by passing it the string. When you do that, it will give you the dictionary inside a dictionary, etc. that the string's contents represent. But I see you understand it now. Happy I could help a little. – Karl Knechtel Jan 19 '22 at 22:48
  • Got it, thanks a lot! – Susomejak Jan 20 '22 at 10:58

1 Answers1

0

Firstly, you must open this JSON file and let the json library parse this file, resulting in a loaded dictionary. See Reading JSON from a file? for more information. Once you have your dictionary, which I'll call users, you can perform this dictionary comprehension:

import json

# Load the file into a `users` (nested) dictionary
with open("file.json", "r") as f:
    users = json.load(f)

name_to_ids = {
    person["element"]["name"]: person["ID"]
    for person in users
}

which outputs:

{'Ana': '1234', 'Bob': '5678', 'Chloe': '8912'}

Note that this can cause issues if there are people with overlapping names! For example:

# I've simply copied this into the .py file for simplicity.
# You'll want to use the JSON parsing method from the Stack Overflow I linked above.
users = [
    {
        "element": {
            "name": "Ana",
            "bio": "xx",
            "type": "female"
        },
        "ID": "1234",
        "status": "STOPPED"
    },
    {
         "element": {
            "name": "Ana",
            "bio": "xy",
            "type": "male"
        },
        "ID": "5678",
        "status": "STOPPED"
    }
]

name_to_ids = {
    person["element"]["name"]: person["ID"]
    for person in users
}

print(name_to_ids)

Outputs:

{'Ana': '5678'}
Tom Aarsen
  • 1,170
  • 2
  • 20
  • This is a valiant effort, but it is not suitable for the problem that OP actually turns out to have - which is with actually parsing the JSON data. – Karl Knechtel Jan 19 '22 at 12:03
  • Ah, indeed. I see their comments reveal a deeper issue here. – Tom Aarsen Jan 19 '22 at 12:07
  • Thank you, I appreciate your effort very much. I thought that loads should be used differently because I have dict inside of dict but seems that I was wrong. Thank you for explanation and taking your time to help! – Susomejak Jan 19 '22 at 12:15
  • 1
    Luckily, no! The `json` module takes care of it all for us. – Tom Aarsen Jan 19 '22 at 12:16
  • 1
    That's the issue when you switch from c to python ahahha. You are not used to not having to take care of everything by yourself. – Susomejak Jan 19 '22 at 12:19
  • Welcome to the beauty that is Python, then! It's quite an adjustment, but you'll miss the simplicity and elegance of some Pythonic solutions once you return back to some other language. At least, I know I do. – Tom Aarsen Jan 19 '22 at 12:20