Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Working with JSON and CSV Data

Working with JSON and CSV Data

Absolutely, working with JSON (JavaScript Object Notation) and CSV (Comma-Separated Values) data is a common task in data manipulation and exchange. Here's how to handle both formats in Python:

Working with JSON:

1. JSON Basics:

  • JSON is a lightweight data interchange format.
  • It uses key-value pairs and supports nested structures.

2. Importing the json Module:

  • Import the built-in json module to work with JSON data.

3. Parsing JSON:

  • Use json.loads() to parse JSON strings into Python data structures (dictionaries, lists, etc.).

4. Creating JSON:

  • Use json.dumps() to convert Python data structures into JSON strings.
  • Specify additional options like indent for pretty printing.

5. Working with Files:

  • Read JSON data from a file using json.load().
  • Write JSON data to a file using json.dump().

Working with CSV:

1. CSV Basics:

  • CSV is a plain text format for tabular data.
  • Each line represents a row, and values are separated by commas (or other delimiters).

2. Importing the csv Module:

  • Import the built-in csv module to work with CSV data.

3. Reading CSV Data:

  • Use csv.reader() to read CSV data from a file.
  • Iterate through rows and process the data.

4. Writing CSV Data:

  • Use csv.writer() to write CSV data to a file.
  • Write rows with appropriate values and delimiters.

Example:

Here's an example that demonstrates reading JSON data from a file, processing it, and then writing CSV data to another file:

import json
import csv

# Reading JSON data from a file
with open("data.json") as json_file:
data = json.load(json_file)

# Extracting and processing JSON data
people = data["people"]
csv_data = []
for person in people:
csv_data.append([person["name"], person["age"], person["city"]])

# Writing CSV data to a file
with open("people.csv", "w", newline="") as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(["Name", "Age", "City"]) # Write header
csv_writer.writerows(csv_data) # Write rows
   

 

 

In this example, we read JSON data from a file, extract specific information, process it, and then write CSV data to another file.

Handling JSON and CSV effectively is important when working with data from different sources and in various formats. It's also useful for data exchange between different systems and tools.