| |
To achieve this task, you can use the pandas
library to read the Excel file and then convert the data into the desired JSON format. Below is a step-by-step guide and the corresponding Python code to accomplish this:
Install the required libraries: Make sure you have pandas
and openpyxl
installed. You can install them using pip if you haven’t already:
pip install pandas openpyxl
Read the Excel file: Use pandas
to read the Excel file and convert it to a DataFrame.
Transform the data: Modify the DataFrame to match the desired JSON structure.
Save to JSON file: Write the transformed data to a JSON file.
Here is the complete Python code to achieve this:
import pandas as pd
# Step 1: Read the Excel file
file_path = 'mobile.xlsx'
df = pd.read_excel(file_path)
# Step 2: Transform the data
# Initialize an empty list to store the transformed data
transformed_data = []
# Iterate over each row in the DataFrame
for index, row in df.iterrows():
# Create a dictionary for each row with the desired structure
transformed_row = {
"mobile_id": index + 1, # Assuming mobile_id starts from 1
"mobile": None, # As per the desired JSON format
"code": 0, # As per the desired JSON format
"province": row['Province'],
"city": row['City'],
"sp": row['SP'],
"is_updated": 1 # As per the desired JSON format
}
# Append the dictionary to the list
transformed_data.append(transformed_row)
# Step 3: Save the transformed data to a JSON file
output_file = 'mobile.json'
with open(output_file, 'w', encoding='utf-8') as json_file:
import json
json.dump(transformed_data, json_file, ensure_ascii=False, indent=4)
print(f"Data has been successfully written to {output_file}")
pd.read_excel(file_path)
function reads the Excel file into a DataFrame.json.dump()
function to write the list of dictionaries to a JSON file.mobile_id
is generated based on the row index, starting from 1.mobile
field is set to None
as per the desired JSON format.code
and is_updated
fields are set to 0
and 1
, respectively, as per the desired JSON format.Make sure the Excel file mobile.xlsx
is in the same directory as your script, or provide the full path to the file. The resulting mobile.json
file will be created in the same directory.
系列Course并未All上架,处于先行测试阶段