How to find the outer keys in a nested dictionary

Question:

I have a large nested JSON in python, which I’ve converted to a dictionary. In it, there’s a key called ‘achievements’ in some sub-dictionary (don’t know how far it’s nested). This sub-dictionary is itself either an element of a list, or the value of a key in a larger dictionary.

Assuming all I know is that this key is called ‘achievements’, how can I get its value? It’s fine to assume that the key’s ‘achievements’ name is unique in the entire dictionary at all levels.

Asked By: Inertial Ignorance

||

Answers:

You can use JSONPath to find this and almost any sort of search path within json quite easily. See the jsonpath-ng library for an example.

In your case, the JSONPath $..achievements will give you what you need.

PS: While you can absolutely write a recursive function to search through the dictionary, JsonPath allows you to write more complex queries, retrieve multiple results, etc. and is a more powerful tool to have in your arsenal.

Answered By: Ani
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.