PYTHON WORKING JSON FILES
Python provides several libraries for reading, loading, and saving data to JSON files. Here is an explanation of how to do this using two popular libraries: json
and pandas
.
Using the json
library:
The json
library is a built-in library in Python for encoding and decoding JSON data. It provides two main functions for reading and writing JSON data to a file: json.dump()
and json.load()
.
Here’s an example of how to use these functions:
import json
# Saving JSON data to a file
data = {
"name": "John Doe",
"age": 32,
"city": "New York"
}
# The `with` statement is used to open the file and automatically close it after the indented code is executed.
# The "w" argument tells the open function to open the file in write mode.
with open("data.json", "w") as file:
# The `json.dump()` function takes two arguments: the JSON data, and the file-like object to write to.
json.dump(data, file)
# Loading JSON data from a file
# The "r" argument tells the open function to open the file in read mode.
with open("data.json", "r") as file:
# The `json.load()` function takes one argument: the file-like object to read from.
data = json.load(file)
# The `print` function is used to display the loaded data on the screen.
print(data)
Using the pandas
library:
The pandas
library is a popular library for data analysis and manipulation in Python. It provides two main functions for reading and writing JSON data to a file: pandas.read_json()
and DataFrame.to_json()
.
Here’s an example of how to use these functions:
import pandas as pd
# Loading JSON data into a DataFrame
data = {
"name": ["John Doe", "Jane Doe"],
"age": [32, 29],
"city": ["New York", "Los Angeles"]
}
# The `pd.DataFrame` function is used to create a DataFrame from a dictionary.
df = pd.DataFrame(data)
# Saving DataFrame data to a JSON file
# The `to_json` function takes two arguments: the file name, and the "orient" argument which specifies the format of the JSON file.
# The "records" orientation represents the data as a list of dictionaries, where each dictionary represents a row in the DataFrame.
df.to_json("data.json", orient="records")
# Loading JSON data from a file into a DataFrame
# The `pd.read_json` function takes one argument: the file name.
df = pd.read_json("data.json")
# The `print` function is used to display the loaded DataFrame on the screen.
print(df)
Follow,Like and Share