在Python中存储JSON数据可以使用以下几种方法:
示例代码:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 存储JSON数据到文件
with open("data.json", "w") as file:
json.dump(data, file)
# 将JSON数据转换为字符串
json_str = json.dumps(data)
示例代码(使用pickle库):
import pickle
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 存储JSON数据到文件
with open("data.pickle", "wb") as file:
pickle.dump(data, file)
# 从文件中加载JSON数据
with open("data.pickle", "rb") as file:
loaded_data = pickle.load(file)
示例代码(使用MySQL数据库):
import mysql.connector
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 连接到数据库
cnx = mysql.connector.connect(user='username', password='password',
host='localhost', database='mydatabase')
# 创建表
cursor = cnx.cursor()
cursor.execute("CREATE TABLE json_data (id INT AUTO_INCREMENT PRIMARY KEY, data JSON)")
# 插入JSON数据
insert_query = "INSERT INTO json_data (data) VALUES (%s)"
data_json = json.dumps(data)
cursor.execute(insert_query, (data_json,))
# 提交更改并关闭连接
cnx.commit()
cursor.close()
cnx.close()
以上是在Python中存储JSON数据的几种常见方法,具体选择哪种方法取决于具体需求和场景。
领取专属 10元无门槛券
手把手带您无忧上云