Python provides built-in support for working with JSON (JavaScript Object Notation) data. With the help of the json module, you can easily encode Python objects into JSON strings and decode JSON strings into Python objects.
This makes it easy to exchange data between different programming languages and web applications that use JSON as a common data format. In this way, Python provides a simple and efficient way to work with JSON data.
In Python, JSON (JavaScript Object Notation) is a lightweight data interchange format that is used to transmit and store data in a structured way.
JSON is a text-based format that is easy for both humans and machines to read and write.
It is often used in web applications as a data format for sending and receiving data between servers and clients.
In Python, the json module provides a set of functions to encode and decode JSON data.
You can use these functions to convert Python objects into JSON format and vice versa.
JSON data is represented in Python as a dictionary, list, string, number, or boolean value, depending on its structure.
Python’s support for JSON makes it easy to work with JSON data in a variety of contexts, such as web development, data analysis, and machine learning.
Python provides a built-in json module that you can use to work with JSON data.
The json module provides functions to encode Python objects into JSON format and decode JSON data into Python objects.
Here is a brief overview of how to use the json module in Python:
Encoding JSON Data: To encode Python objects into JSON format, you can use the json.dumps() function.
This function takes a Python object as input and returns a string representing the JSON data.
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data)
print(json_data)
This will output the following JSON string:
{"name": "John", "age": 30, "city": "New York"}
To decode JSON data into Python objects, you can use the json.loads() function.
This function takes a JSON string as input and returns a Python object.
import json
json_data = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_data)
print(data)
This will output the following Python dictionary:
{'name': 'John', 'age': 30, 'city': 'New York'}
You can also read and write JSON data from files using the json.dump() and json.load() functions.
The json.dump() function writes a Python object to a file in JSON format, while the json.load() function reads a JSON file and returns a Python object.
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
with open('data.json', 'w') as f:
json.dump(data, f)
with open('data.json', 'r') as f:
data = json.load(f)
print(data)
This will output the same dictionary as before:
{'name': 'John', 'age': 30, 'city': 'New York'}
These are the basic steps for working with JSON data in Python using the built-in json module.
There are many more functions and options available in the json module, depending on your specific needs.
To convert a Python object to JSON format, you can use the json.dumps() function. This function takes a Python object as input and returns a JSON-formatted string.
Here’s an example:
import json
# define a Python dictionary
data = {
"name": "John Smith",
"age": 30,
"is_active": True
}
# convert the Python object to a JSON string
json_string = json.dumps(data)
# print the JSON string
print(json_string)
In this example, we define a Python dictionary and convert it to a JSON string using json.dumps(). The resulting JSON string looks like this:
{"name": "John Smith", "age": 30, "is_active": true}
{"name": "John Smith", "age": 30, "is_active": true}
Note that the json.dumps() function will not handle all Python objects. For example, if your Python object contains a custom class or function, json.dumps() will raise a TypeError.
In general, you should only use json.dumps() with simple Python objects like strings, numbers, lists, and dictionaries.
If you want to customize the JSON formatting, you can use the indent argument of json.dumps().
For example:
import json
# define a Python dictionary
data = {
"name": "John Smith",
"age": 30,
"is_active": True
}
# convert the Python object to a pretty-printed JSON string
json_string = json.dumps(data, indent=2)
# print the JSON string
print(json_string)
In this example, we use the indent argument to specify a two-space indentation for the JSON output. The resulting JSON string looks like this:
{
"name": "John Smith",
"age": 30,
"is_active": true
}
To convert Python objects into JSON strings and print the values, you can use the json.dumps() function and the print() function. Here’s an example:
import json
# define a Python object
data = {
"name": "John Smith",
"age": 30,
"is_active": True
}
# convert the Python object to a JSON string
json_string = json.dumps(data)
# print the JSON string and the values of the Python object
print(json_string)
print(data['name'])
print(data['age'])
print(data['is_active'])
In this example, we define a Python object and convert it to a JSON string using json.dumps(). We then print the JSON string and the values of the Python object using the print() function. The output of this code will be: Note that the values printed using print() are the same as the values in the original Python object. Converting a Python object to JSON and back to a Python object may not always preserve the exact same data types, but for simple objects like this one, the values will be the same.
To convert a Python dictionary into JSON format, you can use the json.dumps() function. Here’s an example:
import json
# define a Python dictionary
data = {
"name": "John Smith",
"age": 30,
"is_active": True
}
# convert the Python dictionary to a JSON string
json_string = json.dumps(data)
# print the JSON string
print(json_string)
In this example, we define a Python dictionary and convert it to a JSON string using json.dumps(). The resulting JSON string looks like this:
{"name": "John Smith", "age": 30, "is_active": true}
Note that the keys in the Python dictionary become the property names in the resulting JSON object, and the values become the corresponding property values. If you want to customize the JSON formatting, you can use the indent argument of json.dumps(). For example:
import json
# define a Python dictionary
data = {
"name": "John Smith",
"age": 30,
"is_active": True
}
# convert the Python dictionary to a pretty-printed JSON string
json_string = json.dumps(data, indent=2)
# print the JSON string
print(json_string)
In this example, we use the indent argument to specify a two-space indentation for the JSON output. The resulting JSON string looks like this:
{
"name": "John Smith",
"age": 30,
"is_active": true
}
To convert a Python list into JSON format, you can use the json.dumps() function.
Here’s an example:
import json
# define a Python list
data = ["apple", "banana", "orange"]
# convert the Python list to a JSON string
json_string = json.dumps(data)
# print the JSON string
print(json_string)
In this example, we define a Python list and convert it to a JSON string using json.dumps(). The resulting JSON string looks like this:
["apple", "banana", "orange"]
Note that the items in the Python list become the values in the resulting JSON array.
If you want to customize the JSON formatting, you can use the indent argument of json.dumps().
For example:
import json
# define a Python list
data = ["apple", "banana", "orange"]
# convert the Python list to a pretty-printed JSON string
json_string = json.dumps(data, indent=2)
# print the JSON string
print(json_string)
In this example, we use the indent argument to specify a two-space indentation for the JSON output.
The resulting JSON string looks like this:
[
"apple",
"banana",
"orange"
]
To convert a Python tuple into JSON format, you can first convert the tuple to a list, and then use the json.dumps() function. Here’s an example:
import json
# define a Python tuple
data = ("apple", "banana", "orange")
# convert the Python tuple to a list
data_list = list(data)
# convert the Python list to a JSON string
json_string = json.dumps(data_list)
# print the JSON string
print(json_string)
In this example, we define a Python tuple and convert it to a list using the list() function.
We then convert the Python list to a JSON string using json.dumps(). The resulting JSON string looks like this:
["apple", "banana", "orange"]
Note that the items in the Python tuple become the values in the resulting JSON array.
If you want to customize the JSON formatting, you can use the indent argument of json.dumps().
For example:
import json
# define a Python tuple
data = ("apple", "banana", "orange")
# convert the Python tuple to a list
data_list = list(data)
# convert the Python list to a pretty-printed JSON string
json_string = json.dumps(data_list, indent=2)
# print the JSON string
print(json_string)
In this example, we use the indent argument to specify a two-space indentation for the JSON output.
The resulting JSON string looks like this:
[
"apple",
"banana",
"orange"
]
To convert a Python string into a JSON format, you need to first create a Python dictionary or list with the string as its value, and then use the json.dumps() function to convert it to a JSON string.
Here’s an example:
import json
# define a Python string
data = "hello world"
# create a dictionary with the string as its value
data_dict = {"message": data}
# convert the dictionary to a JSON string
json_string = json.dumps(data_dict)
# print the JSON string
print(json_string)
In this example, we define a Python string and create a dictionary with the string as its value. We then convert the dictionary to a JSON string using json.dumps(). The resulting JSON string looks like this:
{"message": "hello world"}
Note that the string value is now a JSON string value and is enclosed in double quotes. If you want to customize the JSON formatting, you can use the indent argument of json.dumps().
For example:
import json
# define a Python string
data = "hello world"
# create a dictionary with the string as its value
data_dict = {"message": data}
# convert the dictionary to a pretty-printed JSON string
json_string = json.dumps(data_dict, indent=2)
# print the JSON string
print(json_string)
In this example, we use the indent argument to specify a two-space indentation for the JSON output.
The resulting JSON string looks like this:
{
"message": "hello world"
}
To convert a Python integer into a JSON format, you can simply create a dictionary with the integer as its value, and then use the json.dumps() function to convert it to a JSON string.
Here’s an example:
import json
# define a Python integer
data = 42
# create a dictionary with the integer as its value
data_dict = {"number": data}
# convert the dictionary to a JSON string
json_string = json.dumps(data_dict)
# print the JSON string
print(json_string)
In this example, we define a Python integer and create a dictionary with the integer as its value.
We then convert the dictionary to a JSON string using json.dumps().
The resulting JSON string looks like this:
{"number": 42}
Note that the integer value is now a JSON number value and is not enclosed in quotes.
If you want to customize the JSON formatting, you can use the indent argument of json.dumps().
For example:
import json
# define a Python integer
data = 42
# create a dictionary with the integer as its value
data_dict = {"number": data}
# convert the dictionary to a pretty-printed JSON string
json_string = json.dumps(data_dict, indent=2)
# print the JSON string
print(json_string)
In this example, we use the indent argument to specify a two-space indentation for the JSON output.
The resulting JSON string looks like this:
{
"number": 42
}
To convert a Python float into a JSON format, you can simply create a dictionary with the float as its value, and then use the json.dumps() function to convert it to a JSON string. Here’s an example:
import json
# define a Python float
data = 3.14159
# create a dictionary with the float as its value
data_dict = {"pi": data}
# convert the dictionary to a JSON string
json_string = json.dumps(data_dict)
# print the JSON string
print(json_string)
In this example, we define a Python float and create a dictionary with the float as its value. We then convert the dictionary to a JSON string using json.dumps().
The resulting JSON string looks like this:
{"pi": 3.14159}
Note that the float value is now a JSON number value and is not enclosed in quotes.
If you want to customize the JSON formatting, you can use the indent
argument of json.dumps()
.
For example:
import json
# define a Python float
data = 3.14159
# create a dictionary with the float as its value
data_dict = {"pi": data}
# convert the dictionary to a pretty-printed JSON string
json_string = json.dumps(data_dict, indent=2)
# print the JSON string
print(json_string)
In this example, we use the indent argument to specify a two-space indentation for the JSON output. The resulting JSON string looks like this:
{
"pi": 3.14159
}
To convert a Python True value into JSON format, you can simply create a dictionary with the boolean as its value, and then use the json.dumps() function to convert it to a JSON string. Here’s an example:
import json
# define a Python boolean
data = True
# create a dictionary with the boolean as its value
data_dict = {"is_true": data}
# convert the dictionary to a JSON string
json_string = json.dumps(data_dict)
# print the JSON string
print(json_string)
In this example, we define a Python boolean and create a dictionary with the boolean as its value. We then convert the dictionary to a JSON string using json.dumps(). The resulting JSON string looks like this:
{"is_true": true}
Note that the True value is now a JSON boolean value and is not enclosed in quotes. If you want to customize the JSON formatting, you can use the indent argument of json.dumps(). For example:
import json
# define a Python boolean
data = True
# create a dictionary with the boolean as its value
data_dict = {"is_true": data}
# convert the dictionary to a pretty-printed JSON string
json_string = json.dumps(data_dict, indent=2)
# print the JSON string
print(json_string)
In this example, we use the indent argument to specify a two-space indentation for the JSON output. The resulting JSON string looks like this:
{
"is_true": true
}
To convert a Python False value into JSON format, you can follow the same approach as for converting True. You can create a dictionary with the boolean as its value, and then use the json.dumps() function to convert it to a JSON string. Here’s an example:
import json
# define a Python boolean
data = False
# create a dictionary with the boolean as its value
data_dict = {"is_false": data}
# convert the dictionary to a JSON string
json_string = json.dumps(data_dict)
# print the JSON string
print(json_string)
In this example, we define a Python boolean and create a dictionary with the boolean as its value. We then convert the dictionary to a JSON string using json.dumps(). The resulting JSON string looks like this:
{"is_false": false}
{"is_false": false}
Note that the False value is now a JSON boolean value and is not enclosed in quotes. If you want to customize the JSON formatting, you can use the indent argument of json.dumps(). For example:
import json
# define a Python boolean
data = False
# create a dictionary with the boolean as its value
data_dict = {"is_false": data}
# convert the dictionary to a pretty-printed JSON string
json_string = json.dumps(data_dict, indent=2)
# print the JSON string
print(json_string)
In this example, we use the indent argument to specify a two-space indentation for the JSON output. The resulting JSON string looks like this:
{
"is_false": false
}
To convert a Python None value into JSON format, you can simply assign it as a value in a dictionary and then use the json.dumps() function to convert it to a JSON string. Here’s an example:
import json
# define a Python None value
data = None
# create a dictionary with the None value as its value
data_dict = {"value": data}
# convert the dictionary to a JSON string
json_string = json.dumps(data_dict)
# print the JSON string
print(json_string)
In this example, we define a Python None value and create a dictionary with the value as its value. We then convert the dictionary to a JSON string using json.dumps(). The resulting JSON string looks like this:
{"value": null}
Note that the None value is now a JSON null value and is not enclosed in quotes. If you want to customize the JSON formatting, you can use the indent argument of json.dumps(). For example:
import json
# define a Python None value
data = None
# create a dictionary with the None value as its value
data_dict = {"value": data}
# convert the dictionary to a pretty-printed JSON string
json_string = json.dumps(data_dict, indent=2)
# print the JSON string
print(json_string)
In this example, we use the indent argument to specify a two-space indentation for the JSON output. The resulting JSON string looks like this:
{
"value": null
}
Here are some of the most common uses of Python JSON with examples:
You can use the json.dumps() function to convert Python objects into JSON format.
Here’s an example:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data)
print(json_data)
Output:
{"name": "John", "age": 30, "city": "New York"}
You can use the json.loads() function to convert JSON data into Python objects. Here’s an example:
import json
json_data = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_data)
print(data)
You can use the json.loads() function to convert JSON data into Python objects. Here’s an example:
import json
json_data = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_data)
print(data)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
You can read and write JSON data to and from files using the json.dump() and json.load() functions.
Here’s an example:
import json data = { “name”: “John”, “age”: 30, “city”: “New York” } # Write data to a file with open(“data.json”, “w”) as f: json.dump(data, f) # Read data from a file with open(“data.json”, “r”) as f: data = json.load(f) print(data)
Output:
{‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
You can use the json.JSONDecoder()
class to validate JSON data. Here’s an example:
import json
json_data = '{"name": "John", "age": 30, "city": "New York"}'
try:
data = json.JSONDecoder().decode(json_data)
print(data)
except ValueError as e:
print("Invalid JSON:", e)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
You can use the json.JSONDecoder() class to convert JSON data to Python objects. Here’s an example:
import json
json_data = '{"name": "John", "age": 30, "city": "New York"}'
data = json.JSONDecoder().decode(json_data)
print(data)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
You can use the json.JSONEncoder() class to convert Python objects to JSON data. Here’s an example:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = json.JSONEncoder().encode(data)
print(json_data)
Output:
{"name": "John", "age": 30, "city": "New York"}
You can use Python’s json module to send and receive JSON data over a network. Here’s an example:
import json
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
# set port number
port = 9999
# bind the socket to a public host and port
s.bind((host, port))
# become a server socket
s.listen(1)
while True:
# establish a connection
conn, addr = s.accept()
print('Connected by', addr)
# receive data from client
data = conn.recv(1024).decode()
# convert JSON data to Python object
obj = json.loads(data)
# process data
print(obj)
# convert Python object to JSON data
json_data = json.dumps(obj)
# send data back to client
conn.send(json_data.encode())
# close the connection
conn.close()
You can use Python’s list comprehension and conditional statements to filter JSON data. Here’s an example:
import json
json_data = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}, {"name": "Bob", "age": 40}]'
data = json.loads(json_data)
# filter data by age
filtered_data = [d for d in data if d['age'] > 30]
print(filtered_data)
Output:
[{'name': 'Bob', 'age': 40}]
You can use Python’s dictionary methods to modify JSON data. Here’s an example:
import json
json_data = '{"name": "John", "age": 30}'
data = json.loads(json_data)
# modify data
data['age'] = 35
# convert Python object to JSON data
json_data = json.dumps(data)
print(json_data)
Output:
{"name": "John", "age": 35}
You can use Python’s exception handling to handle errors that occur when working with JSON data. Here’s an example:
import json
json_data = '{"name": "John", "age": 30, "city": "New York"}'
try:
data = json.loads(json_data)
print(data)
except json.JSONDecodeError as e:
print("Invalid JSON:", e)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
You can use Python’s json module to read and write JSON data to a file. Here’s an example:
import json
# write JSON data to a file
data = {"name": "John", "age": 30}
with open('data.json', 'w') as f:
json.dump(data, f)
# read JSON data from a file
with open('data.json', 'r') as f:
data = json.load(f)
print(data)
Output:
{'name': 'John', 'age': 30}
You can use Python’s json module to serialize and deserialize custom objects. To do this, you need to define a custom encoder and decoder. Here’s an example:
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def person_encoder(obj):
if isinstance(obj, Person):
return {"name": obj.name, "age": obj.age}
return obj
def person_decoder(obj):
if 'name' in obj and 'age' in obj:
return Person(obj['name'], obj['age'])
return obj
# serialize custom object to JSON
person = Person("John", 30)
json_data = json.dumps(person, default=person_encoder)
print(json_data)
# deserialize JSON data to custom object
data = json.loads(json_data, object_hook=person_decoder)
print(data.name, data.age)
Output:
{"name": "John", "age": 30}
John 30
You can use Python’s jsonschema module to validate JSON data against a schema. Here’s an example:
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
},
"required": ["name", "age"]
}
# valid data
data = {"name": "John", "age": 30}
validate(data, schema)
# invalid data
data = {"name": "Jane"}
validate(data, schema)
Output:
jsonschema.exceptions.ValidationError: 'age' is a required property
You can use Python’s pandas library to convert JSON data to a Pandas DataFrame. Here’s an example:
import json
import pandas as pd
json_data = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}, {"name": "Bob", "age": 40}]'
data = json.loads(json_data)
df = pd.DataFrame(data)
print(df)
Output:
name age
0 John 30
1 Jane 25
2 Bob 40
JSON is a popular format for APIs, so if you’re building a Python application that interacts with APIs, you’ll likely need to work with JSON data. Python’s requests library makes it easy to send and receive JSON data from APIs. Here’s an example:
import requests
import json
# make a request to an API that returns JSON data
response = requests.get('https://api.example.com/data')
json_data = response.json()
# print the JSON data
print(json.dumps(json_data, indent=4))
Sometimes, JSON data can be difficult to read because it’s all on one line. Python’s json module includes a function called dumps that allows you to pretty print JSON data with indentation. Here’s an example:
import json
data = {"name": "John", "age": 30}
# pretty print JSON data
print(json.dumps(data, indent=4))
Output:
{
"name": "John",
"age": 30
}
If you need to convert JSON data to XML, you can use Python’s xmltodict library. Here’s an example:
import json
import xmltodict
json_data = '{"name": "John", "age": 30}'
# convert JSON data to XML
xml_data = xmltodict.unparse(json.loads(json_data))
print(xml_data)
Output:
John
30
If you need to convert JSON data to YAML, you can use Python’s PyYAML library. Here’s an example:
import json
import yaml
json_data = '{"name": "John", "age": 30}'
# convert JSON data to YAML
yaml_data = yaml.dump(json.loads(json_data), default_flow_style=False)
print(yaml_data)
Output:
age: 30
name: John
You can use Python JSON to read and write JSON files. Here’s an example:
import json
# read JSON data from a file
with open('data.json') as f:
data = json.load(f)
# modify the JSON data
data['name'] = 'John Smith'
# write the modified JSON data to a file
with open('data.json', 'w') as f:
json.dump(data, f)
If you’re building a command-line application that needs to work with JSON data, you can use Python’s argparse library to parse JSON data from the command line. Here’s an example:
import argparse
import json
# define the command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--json', type=json.loads, required=True)
# parse the command line arguments
args = parser.parse_args()
# use the JSON data
print(args.json)
You can run this script with a command like this:
python script.py --json '{"name": "John", "age": 30}'
If you’re building a Python application that sends HTTP requests, you can use Python JSON to send JSON data in the request body. Here’s an example:
import requests
import json
# define the JSON data
data = {"name": "John", "age": 30}
# send a POST request with the JSON data in the request body
response = requests.post('https://api.example.com/data', json=data)
# print the response
print(response.json())
If you’re building a Python application that uses websockets, you can use Python JSON to send and receive JSON data over the websocket connection. Here’s an example:
import json
import asyncio
import websockets
async def websocket():
# connect to the websocket server
async with websockets.connect('wss://api.example.com/data') as websocket:
# send JSON data over the websocket connection
data = {"name": "John", "age": 30}
await websocket.send(json.dumps(data))
# receive JSON data from the websocket connection
response = await websocket.recv()
json_data = json.loads(response)
print(json_data)
asyncio.run(websocket())
If you need to work with large JSON data files in your Python program, you can use the ijson library, which allows you to iterate over JSON data without loading it all into memory at once. Here’s an example:
import ijson
# iterate over JSON data in a file
with open('data.json') as f:
parser = ijson.parse(f)
for prefix, event, value in parser:
if prefix == 'person.name':
print(value)
To parse JSON and convert it to a Python object, you can use the json.loads()
function. This function takes a JSON string as input and returns a corresponding Python object. Here’s an example:
import json
# define a JSON string
json_string = '{"name": "John Smith", "age": 30, "is_active": true}'
# parse the JSON string to a Python object
data = json.loads(json_string)
# access the data as a Python object
print(data['name']) # prints "John Smith"
print(data['age']) # prints 30
print(data['is_active']) # prints True
In this example, we define a JSON string and parse it using json.loads(). The resulting Python object is a dictionary that we can access using the usual dictionary syntax. Note that the json.loads() function will raise an error if the input string is not valid JSON. You can catch this error using a try-except block. For example:
import json
# define an invalid JSON string
json_string = '{"name": "John Smith", "age": 30, "is_active": true'
try:
# try to parse the JSON string to a Python object
data = json.loads(json_string)
except json.JSONDecodeError as e:
# handle the JSON decode error
print(f"Invalid JSON string: {e}")
In this example, we define an invalid JSON string (missing a closing bracket).
When we try to parse it using json.loads(), it will raise a json.JSONDecodeError.
We catch this error using a try-except block and handle it by printing an error message.
1-What does JSON stand for in Python?
a. Java Syntax Object Notation
b. JavaScript Object Notation
c. JSON Object Notation
d. Jupyter Scripting Object Notation
2-How does Python represent JSON data internally?
a. List
b. Tuple
c. Dictionary
d. Set
3-Which Python module is used for working with JSON?
a. jsonize
b. jsondata
c. jsonlib
d. json
4-How do you encode a Python object into a JSON-formatted string?
a. json.encode()
b. json.to_string()
c. json.dumps()
d. json.serialize()
5-What does the json.dumps() function do?
a. Decodes JSON data
b. Encodes Python objects into JSON format
c. Reads JSON data from a file
d. Validates JSON data
6-How do you decode a JSON-formatted string into a Python object?
a. json.parse()
b. json.loads()
c. json.decode()
d. json.from_string()
7-What is the purpose of the json.dump() function?
a. Encodes Python objects into JSON format
b. Decodes JSON data
c. Writes JSON data to a file
d. Reads JSON data from a file
8-How can you pretty print JSON data with an indentation of 2 spaces?
a. json.pretty_print(data, 2)
b. json.dumps(data, pretty=True, indent=2)
c. json.dumps(data, indent=2)
d. json.format(data, indent=2)
9-Which Python data type is used to represent JSON boolean values?
a. bool
b. boolean
c. int
d. str
10-How can you convert a Python list into JSON format?
a. json.list(data)
b. json.dumps(data)
c. json.encode(data)
d. json.list_to_json(data)
11-To convert a Python integer into a JSON format, what function do you use?
a. json.integer(data)
b. json.encode(data)
c. json.number(data)
d. json.dumps(data)
12-How do you handle Python None values when converting to JSON?
a. Use json.dump_none()
b. json.dumps(data, none_as_null=True)
c. json.dumps(data, default=None)
d. json.encode_none(data)
13-Which library is used to validate JSON data against a schema?
a. jsonschema
b. jsonvalidator
c. jsoncheck
d. jsonverify
14-How can you convert JSON data to a Pandas DataFrame?
a. pd.json_to_df(json_data)
b. pd.DataFrame.from_json(json_data)
c. pd.read_json(json_data)
d. pd.json_data_to_dataframe(json_data)
15-In a web development scenario, what is a common use of Python JSON?
a. Writing complex algorithms
b. Handling user authentication
c. Exchanging data between server and client
d. Managing database connections
Answers:
1-b ,2-c ,3-d 4-c 5-b 6-b 7-c 8-c 9-a 10-b 11-d 12-c 13-a 14-c 15-c