350-401 · Question #443
350-401 Question #443: Real Exam Question with Answer & Explanation
The correct answer is A: return (json.dumps({d['hostname']: d['serialNumber'] for d in json.loads(test_json)['response']})). To transform a JSON string into a specific JSON object, the Python function must parse the input, extract the required key-value pairs using a dictionary comprehension, and then serialize the resulting dictionary back to a JSON string.
Question
Which line must be added in the Python function to return the JSON object {"cat_9k": "FXS1932Q2SE")?
Options
- Areturn (json.dumps({d['hostname']: d['serialNumber'] for d in json.loads(test_json)['response']}))
- Breturn (json.dumps({for d in json.loads(test_json)['response']: d['hostname']: d['serialNumber']}))
- Creturn (json.loads({d['hostname']: d['serialNumber'] for d in json.dumps(test_json)['response'}))
- Dreturn (json.loads({for d in json.dumps(test_json)['response']: d['hostname']: d['serialNumber']}))
Explanation
To transform a JSON string into a specific JSON object, the Python function must parse the input, extract the required key-value pairs using a dictionary comprehension, and then serialize the resulting dictionary back to a JSON string.
Common mistakes.
- B. This choice contains a syntax error in the dictionary comprehension; the key-value pair must precede the
forloop, i.e.,{{key: value for item in iterable}}. - C. This choice incorrectly uses
json.dumps(test_json)(attempting to serialize an already serialized string) and thenjson.loads()at the end, which would parse a JSON string, not serialize a Python dictionary to JSON. - D. This choice combines a syntax error in the dictionary comprehension (like B) with the incorrect use of
json.loads()for the final output (like C).
Concept tested. Python JSON parsing and dictionary comprehension
Reference. https://docs.python.org/3/library/json.html
Topics
Community Discussion
No community discussion yet for this question.