1

I've a JSON File:

[


{
    "schema":{"id":1},
    "rawdata":{},
    "enriched":{"name":"xy1"}
},




{
    "schema":{"id":2},
    "rawdata":{},
    "enriched":{"name":"xy2"}   
},


{ "schma":{"id":3}, "radata":{},"enrichd":{"name":"xy3"} 
},


{ "schema":{"id":3}, "radata":{},"enriched":{"name":"xy3"} 
},


{"name":"xy200"},


{
    "schema":{"id":4},
    "rawdata":{},"enriched":{"name":"xy4"}   
}

]

where I've to filter the numbers of the nested entries from "name" : "xy1". In short words: I need every number after "xy".

My code I already wrote is this:

    for value in data:
   
    if value["enriched"]:
        get_char = value["enriched"]["name"]
        num = get_char[2:]
        print(f"{num}")
        
     
    elif value["enrichd"]:
        get_char = value["enrichd"]["name"]
        num = get_char[2:]
        print(f"{num}")
    
    elif value["name"]:
        get_char = value["name"]
        num = get_char[2:]
        print(f"{num}")
    
    else:
        print("test")

and my error message is this:

1
2

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-155-13d4f2ca308f> in <module>
     52     for value in data:
     53         try:
---> 54             if value["enriched"]:
     55                 get_char = value["enriched"]["name"]
     56                 num = get_char[2:]

KeyError: 'enriched'

But I dont figure out why I the loop doesnt use the elif's I've wrote. Maybe someone could help me :)

  • 1
    [Check if a given key already exists in a dictionary](https://stackoverflow.com/q/1602934/1324033) – Sayse Jan 06 '21 at 14:54
  • It works! Thanks alot mate, have a nice evening :) – christhebliss Jan 06 '21 at 14:58
  • 1
    Does this answer your question? [Check if a given key already exists in a dictionary](https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – Ruli Jan 06 '21 at 21:09

1 Answers1

1

I think this may be the result of a typo rather than anything wrong with your code: you have misspelt “enriched” as “enrichd” in one of your dicts, and thus python will raise a KeyError because there is no “enriched” in your dictionary. Correcting the error should be a simple fix.

On the subject of parsing, say, the number 2 from the string xy2, the simplest method would be to use .strip(“xy”) (although this only works if the characters before the integer will always be the same.)

Edit: using the strip function. Stripping a string simply removes the specified substring from the end and start of the string. So if I had the string ”Hello world”, I would go ”Hello world”.strip(“Hello”) and it will “strip” the word Hello from the start. If I did “area”.strip(“a”), it would return “re” as the a has been removed from each end.