CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingEasy

A developer is writing a Python script that needs to convert a string representing a JSON object into a Python dictionary. The string is `json_string = '{"name": "Alice", "age": 30}'`. Which Python module and function should be used to perform this conversion?

  1. A`json.dumps(json_string)`
  2. B`ast.literal_eval(json_string)`
  3. C`eval(json_string)`
  4. D`json.loads(json_string)`
Show answer & explanation

Correct answer: D. `json.loads(json_string)`

The `json` module in Python provides functions for working with JSON data. Specifically, `json.loads()` is used to parse a JSON formatted string and convert it into a Python object (like a dictionary or list).

Why the other options are wrong

  • A. `json.dumps()` converts a Python object (like a dictionary) *into* a JSON formatted string, the opposite of what's needed.
  • B. `ast.literal_eval()` safely evaluates a string containing a Python literal (like a dictionary or list), but it's for Python syntax, not JSON syntax.
  • C. `eval()` is unsafe as it can execute arbitrary code, and it's not designed for JSON parsing.

Python `json.loads()`

The `json.loads()` function in Python's `json` module is used to deserialize (load) a JSON formatted string into a Python object, typically a dictionary or list.

  • Input must be a valid JSON string.
  • Converts JSON data types to corresponding Python data types.
  • The 's' in `loads` stands for 'string'.

Memory trick: Loads from string, dumps to string, that's the JSON swing!

More Automation, Orchestration and Scripting questions