350-401 · Question #426
An engineer runs the sample code, and the terminal returns this output. Which change to the sample code corrects this issue?
The correct answer is A. Change the JSON method from load() to loads().. To correctly parse a JSON string, the json.loads() method must be used instead of json.load(), which is intended for file-like objects.
Question
An engineer runs the sample code, and the terminal returns this output. Which change to the sample code corrects this issue?
Exhibits
Options
- AChange the JSON method from load() to loads().
- BEnclose null in the test_json string in double quotes
- CUse a single set of double quotes and condense test_json to a single line
- DCall the read() method explicitly on the test_json string
How the community answered
(25 responses)- A44% (11)
- B16% (4)
- C8% (2)
- D32% (8)
Why each option
To correctly parse a JSON string, the `json.loads()` method must be used instead of `json.load()`, which is intended for file-like objects.
The `json.load()` method is designed to deserialize a JSON document from a file-like object, whereas `json.loads()` (load string) is specifically used to deserialize a JSON document directly from a Python string variable; using `json.load()` on a string will result in an error because strings do not have the expected file-like `read()` method.
The JSON `null` literal should not be enclosed in double quotes; doing so would interpret it as the string literal 'null' rather than the null value, potentially leading to incorrect data parsing or a new JSON syntax error.
Condensing a JSON string to a single line or changing the quote type for the string literal itself (assuming it's already a valid Python string) does not address the fundamental issue of using the incorrect JSON parsing method (`load` vs. `loads`).
Calling the `read()` method explicitly on a Python string variable containing JSON would result in an `AttributeError` because string objects do not possess a `read()` method that would return a file-like object suitable for `json.load()`.
Concept tested: Python JSON parsing (load vs loads)
Source: https://docs.python.org/3/library/json.html#json.load
Topics
Community Discussion
No community discussion yet for this question.

