CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingEasy
A developer is writing a Python script that needs to parse a JSON string received from a web API. The JSON string contains user data, including a list of phone numbers. They need to convert this JSON string into a Python dictionary to easily access the data. Which Python module and function should be used for this purpose?
- Ajson.load(json_string)
- Bjson.loads(json_string)
- Cjson.dump(json_string)
- Djson.dumps(json_dict)
Show answer & explanationAnswer & explanation
Correct answer: B. json.loads(json_string)
The `json.loads()` function (load string) is specifically designed to parse a JSON formatted string and convert it into a Python dictionary or list, making it ideal for processing data received from an API.
Why the other options are wrong
- A. `json.load()` is used to deserialize a JSON formatted stream (e.g., reading from a file) into a Python object, not directly from a string.
- C. `json.dump()` is used to serialize a Python object into a JSON formatted stream (e.g., writing to a file), not to parse a string.
- D. `json.dumps()` (dump string) is used to serialize a Python object into a JSON formatted string, which is the opposite of the requirement.
Python `json.loads()`
A function in Python's `json` module used to parse a JSON formatted string and convert it into a Python object (typically a dictionary or list).
- Stands for 'load string'.
- Takes a JSON string as input.
- Returns a Python dictionary, list, or other basic type.
- Raises `json.JSONDecodeError` if the string is not valid JSON.
Memory trick: Load strings, dump objects; use 's' for strings, no 's' for files.