This Python tutorial explains Choose a Data Format: JSON, CSV, TOML, or XML. Follow the example, inspect the output, and practise an input change so you understand the behavior rather than simply copying the syntax.
What This Feature Does
Choose a structured data format based on the data and the exchange requirements.
JSON is common for APIs and supports simple nested types; CSV is convenient for tabular records but has no inherent types; TOML is designed for readable configuration; XML offers structured markup and namespaces. No format automatically validates a business schema.
When to Use It
This technique belongs to data format selection and validation. It is useful when the input, operation and expected outcome are known. Start with a small controlled example before integrating it into a larger workflow.
Step-by-Step Python Example
Read the code once before running it. Notice which values are inputs, which function or method performs the work, and whether the result is returned or stored by changing an existing object.
import csv
import io
import json
import tomllib
record = {"item": "Notebook", "quantity": 3}
print(json.dumps(record))
csv_stream = io.StringIO(newline="")
csv_writer = csv.writer(csv_stream)
csv_writer.writerow([record["item"], record["quantity"]])
print(csv_stream.getvalue().strip())
print(tomllib.loads('item = "Notebook"\nquantity = 3')["quantity"])
Understanding the Code
- First, the imports make csv, io, json, tomllib available. They provide the filesystem, data or standard-library functions used later.
- Find the call print(json.dumps(record)). Its parameters determine the specific operation demonstrated in the title.
- Its purpose is to choose a structured data format based on the data and the exchange requirements. Compare this description against the result printed by the program.
- The print() expressions display a checkable outcome. Print values and exception names are not substitutes for the program result itself.
Expected Output
{"item": "Notebook", "quantity": 3}
Notebook,3
3
Each printed line corresponds to a separate observation in the program. Use the lines to distinguish returned data, changes to existing objects, and status checks.
Important Details and Edge Cases
TOML parsing is read-only in tomllib; writing TOML requires a separate serializer or deliberate text generation.
Decoding a valid file format does not automatically validate the meaning of its data. Confirm expected keys, types, permitted values and resource limits before using externally supplied content.
Second Example: A Useful Variation
import json
serialized_value = json.dumps({'ready': True, 'count': 5})
parsed_value = json.loads(serialized_value)
print(parsed_value['ready'], type(parsed_value['count']).__name__)
JSON booleans and numbers become normal Python bool and int values when parsed.
Variation Output
True int
Practice: Try It Yourself
Convert a two-field record into JSON and CSV, then compare how types are represented.
Begin by copying the example into a separate practice file. Change one input at a time, run it again, and describe why the result changed. If the exercise writes or deletes files, keep it inside a temporary test folder.
Official Python Documentation
For the complete reference, see the Python standard library documentation.
Common Beginner Mistakes
- Assuming a number read from CSV will automatically become an integer.
- Storing secrets in any readable configuration format and assuming serialization encrypts them.
- Decoding a valid file format does not automatically validate the meaning of its data. Confirm expected keys, types, permitted values and resource limits before using externally supplied content.
Key Takeaways
- Choose a structured data format based on the data and the exchange requirements.
- JSON is common for APIs and supports simple nested types; CSV is convenient for tabular records but has no inherent types; TOML is designed for readable configuration; XML offers structured markup and namespaces. No format automatically validates a.
- Avoid this common pitfall: Assuming a number read from CSV will automatically become an integer.