Interview question

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

Argo AI Lidarshark Aug 26, 2021

That's not too hard in Python, depending on how the path is represented.

Argo AI Lidarshark Aug 26, 2021

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

Samsung lumosity OP Aug 26, 2021

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.

Facebook alterego2 Aug 26, 2021

Can you use a Json parser and focus on the edge cases?

VMware gMlg77 Aug 26, 2021

what’s hard about this? isn’t it just basic dfs?

Oscar jorthplus1 Aug 26, 2021

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.

Udacity gqTS64 Aug 26, 2021

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