Asked a following question in faang company interview and would like to ask people how this can be done in 35-40 mins. Write a program which takes a json payload and path as input and return the element that exists at the path, if path is valid. Note : Handle corner cases in the program. In general a json payload can have any type of attribute such as nested objects, arrays, key value pairs and so on. #engineering TC -180K
Can you use a Json parser and focus on the edge cases?
what’s hard about this? isn’t it just basic dfs?
If they're asking for the object at a certain path, just keep going through the json object. For each step of the path, if the key doesn't exist it's not valid, and if it's not a dictionary (besides the last key in the path) then it's not valid. Probably 12 lines of python code.
does the path start at top most element in json? If so, it’s just multi level dict lookup in python. If not dfs/bfs for 1st element in path and then multi level dict lookup
Software Engineering Career
Yesterday
539
Move to India to increase scope?
Working Parents
Yesterday
741
What do you think is wrong with a kid who got rejected by 9 colleges?
Tech Industry
Yesterday
1939
The end of Backdoor Roth?!
India
Yesterday
820
Modi is a legend, will be remembered for centuries to come
Tech Industry
Yesterday
2433
Quitting this Slave life
That's not too hard in Python, depending on how the path is represented.
Python 3.8.3 (default, May 19 2020, 06:50:17) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import json >>> the_json = json.loads('{"hello": {"blind": {"leet": "code"}}}') >>> the_path = 'hello.blind.leet' >>> for path_element in str.split(the_path, '.'): ... object = object[path_element] ... >>> print(object) code Wrap in try block, ezpz 5 minute answer
json payload can contains array and inside array more nested objects. Also path can be invalid as well. Like in case of array payload has 2 elements in array but fetching 3rd. I tried in Java and started handling edge cases first and got confused in the logic.