What are JSON files and how does python process them? (AI) Flashcards

(5 cards)

1
Q

What is a JSON file and its structure?

A

JSON (JavaScript Object Notation) is a lightweight, human-readable data interchange format used to store and transmit structured data.

Structure: It represents data as key-value pairs (similar to Python dictionaries) and ordered lists of values (similar to Python lists).

Purpose: It is widely used for communication between web servers and clients, and for APIs.
File Extension: JSON files use the .json extension.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What Python module is used to work with JSON data?

A

Python has a built-in module named json that provides all the necessary methods for working with JSON data. You must import it into your script to use it.

import json

import json

This module handles the process of serialization (converting Python objects to JSON format) and deserialization (converting JSON data back to Python objects).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you read JSON data from a file in Python?

A

Use the json.load() method with a file object opened in read mode.

import json

with open('data.json', 'r') as f:
    data = json.load(f)
# The 'data' variable is now a Python object (e.g., a dictionary or list)
print(data)

json.load() takes a file object as an argument and returns the corresponding Python object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you write Python data to a JSON file?

A

Use the json.dump() method, passing the Python object and the file object opened in write mode (‘w’)

import json

my_data = {
    "name": "John Doe",
    "age": 30,
    "is_active": True
}

with open('output.json', 'w') as f:
    json.dump(my_data, f, indent=4)

The indent=4 argument is optional but highly recommended to format the output nicely and make it human-readable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the difference between json.load() and json.loads()?

A

The key difference is their input:

json.load(): Reads (deserializes) JSON data from a file object. The “s” is absent.

json.loads(): Reads (deserializes) JSON data from a Python string that contains JSON formatted text. The “s” stands for “string”.

The same distinction applies to the writing methods: json.dump() writes to a file, while json.dumps() creates a JSON-formatted string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly