Skip to content

Instantly share code, notes, and snippets.

@EgehanGundogdu
Created February 13, 2022 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EgehanGundogdu/29846c48816cf6b59dd4e679cbe0d2ec to your computer and use it in GitHub Desktop.
Save EgehanGundogdu/29846c48816cf6b59dd4e679cbe0d2ec to your computer and use it in GitHub Desktop.
json walker with reduce func.
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