Created
February 13, 2022 19:53
-
-
Save EgehanGundogdu/29846c48816cf6b59dd4e679cbe0d2ec to your computer and use it in GitHub Desktop.
json walker with reduce func.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
import operator | |
import unittest | |
from typing import List, Union | |
def reduce_json(data: dict, keys: List[Union[str, int]]): | |
if len(keys) == 0: | |
return | |
try: | |
return functools.reduce(operator.getitem, keys, data) | |
except (KeyError, IndexError): | |
return | |
class ReduceJsonTests(unittest.TestCase): | |
def setUp(self) -> None: | |
self.example_data = { | |
"pk": 1, | |
"personal": { | |
"age": 19, | |
"first_name": "john", | |
"last_name": "doe", | |
"address": { | |
"coordinates": {"longitude": "481148", "latitude": "114811"}, | |
"city": "new york", | |
"street": "48. street", | |
"raw": "lorem ipsum dolor sit amet.", | |
}, | |
}, | |
} | |
def test_reduce_json_func(self): | |
self.assertEqual( | |
reduce_json(self.example_data, ["personal", "address", "city"]), | |
"new york", | |
) | |
self.assertEqual(reduce_json(self.example_data, ["personal", "age"]), 19) | |
self.assertEqual(reduce_json(self.example_data, ["pk"]), 1) | |
self.assertIsNone(reduce_json(self.example_data, ["not_exist_key"])) | |
if __name__ == "__main__": | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment