Python search json for key value
There is a JSON like this:
How can I find all P.S.: If no method can do this, can you tell me how to iterate through the JSON?
martineau 115k25 gold badges160 silver badges284 bronze badges asked Dec 27, 2012 at 3:15
3 As I said in my other answer, I don't think there is a way of finding all values associated with the The basic idea is to use the Note: This will only work if the representation is of a JSON
(Python 3) output:
answered Dec 27, 2012 at 18:46
martineaumartineau 115k25 gold badges160 silver badges284 bronze badges I had the same issue just the other day. I wound up just searching through the entire object and accounted for both lists and dicts. The following snippets allows you to search for the first occurrence of a multiple keys.
It returns a dict with the keys being the keys searched for. Haystack is expected to be a Python object already, so you have to do json.loads before passing it to deep_search. Any comments for optimization are welcomed! answered Dec 27, 2012 at 3:53
1 My approach to this problem would be different. As JSON doesn't allow depth first search, so convert the json to a Python Object, feed it to an XML decoder and then extract the Node you are intending to search
martineau 115k25 gold badges160 silver badges284 bronze badges answered Dec 27, 2012 at 6:08
AbhijitAbhijit 60k18 gold badges126 silver badges197 bronze badges 6 Using
answered Dec 27, 2012 at 3:47
jdotjdotjdotjdot 15.5k12 gold badges63 silver badges115 bronze badges Converting the JSON to Python and recursively searching is by far the easiest:
(where a is the string) The example code ignores arrays. Adding that is left as an exercise. answered Dec 27, 2012 at 3:25
Michael LortonMichael Lorton 41.7k26 gold badges95 silver badges137 bronze badges 1 Bearing in mind that json is simply a string, using regular expressions with look-ahead and look-behind can accomplish this task very quickly. Typically, the json would have been extracted from a request to external api, so code to show how that would work has been included but commented out.
answered Feb 12, 2017 at 2:17
Tony MobbsTony Mobbs 1513 silver badges7 bronze badges I don't think there's any way of finding all values associated with P1 without iterating over the whole structure. Here's a recursive way to do it that first deserializes the JSON object into an equivalent Python object. To simplify things most of the work is done via a recursive private nested function.
answered Dec 27, 2012 at 12:58
martineaumartineau 115k25 gold badges160 silver badges284 bronze badges You could also use a generator to search the object after json.load(). Code example from my answer here: https://stackoverflow.com/a/39016088/5250939
answered Aug 18, 2016 at 11:39
Bo SunesenBo Sunesen 8611 gold badge7 silver badges9 bronze badges The question is old, but no answer answered 100%, so this was my solution: what it does:
suggestions:
answered Jul 28 at 14:27
|