Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

python - How can I use if/else in a nested dictionary (JSON - File)?

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...