DevNet Associate (DEVASC) v1.0Software Development and DesignEasy

A developer needs to convert a Python dictionary representing network device data into a JSON formatted string for transmission over an API. The dictionary contains nested structures and various data types. Which Python built-in module and function should be used for this conversion?

  1. Ayaml.dump()
  2. Bxml.etree.ElementTree.tostring()
  3. Cjson.dumps()
  4. Djson.loads()
Show answer & explanation

Correct answer: C. json.dumps()

The `json` module in Python provides functions for working with JSON data. Specifically, `json.dumps()` (dump string) is used to serialize a Python dictionary (or other Python object) into a JSON formatted string.

Why the other options are wrong

  • A. `yaml.dump()` is used for serializing Python objects into YAML format, not JSON.
  • B. `xml.etree.ElementTree.tostring()` is used for serializing XML ElementTree objects into XML formatted strings, not JSON.
  • D. `json.loads()` is used for deserializing a JSON formatted string into a Python object (e.g., dictionary), which is the opposite of the requirement.

JSON Serialization (Python)

JSON serialization in Python is the process of converting Python objects (like dictionaries and lists) into a JSON formatted string. This is typically done using the `json.dumps()` function from the built-in `json` module.

  • Converts Python object to JSON string
  • Uses `json.dumps()` function
  • Commonly used for API communication and data storage
  • Handles basic Python types (dict, list, str, int, float, bool, None)

Memory trick: Dumps 'dumps' Python data into a JSON string.

More Software Development and Design questions