mysql - 将json字符串转换为mysql中的行
问题描述
如何将此json字符串转换为mysql中的mysql行?
"21283":{"count":82,"price":444},"21158":{"count":178,"price":414},"21281":{"count":157,"price":216},"21165":{"count":132,"price":858},"21284":{"count":99,"price":407},"21175":{"count":60,"price":1650},"21282":{"count":50,"price":1440},"21168":{"count":14,"price":4715},"21280":{"count":22,"price":1625}
有什么解决办法吗?
解决方案
根据您的评论,听起来这就是您想要做的:
import json
import pymysql # I am using Python 3
# string is obtained from somewhere (with extra '{' added at beginning and '}' added at end to make it valid JSON)
rec_string = '{"21283":{"count":82,"price":444},"21158":{"count":178,"price":414},"21281":{"count":157,"price":216},"21165":{"count":132,"price":858},"21284":{"count":99,"price":407},"21175":{"count":60,"price":1650},"21282":{"count":50,"price":1440},"21168":{"count":14,"price":4715},"21280":{"count":22,"price":1625}}'
# and converted to a dictionary:
rec = json.loads(rec_string)
conn = pymysql.connect(db='my_db', user='xxxxxxxx', passwd='xxxxxxxx')
cursor = conn.cursor()
for k,v in rec.items():
cursor.execute('insert into test_table(product_id, count, value) values(%s, %s, %s)', (k, v['count'], v['price']))
conn.commit()
推荐阅读
- file - Flutter web - 显示应用程序中生成的 pdf 文件。(Uint8List 格式)
- google-oauth - Google My Business API:出现 404 错误
- python - 基于用户配置文件的 Django 管理员过滤
- c# - C# .NET Core:在 SQL Server 中自动保存 UserId
- r - 从 R 中的 lme4 对象获取单个斜率
- azure - 将自定义 Angular 客户端应用程序与 Azure IoT Central 一起使用
- rest - 资源 ID 是否应该放在 PUT 和 PATCH 请求的 URL 中?
- android - 使用 Chrome 自定义标签时隐藏使用条款提示
- php - PHP [将数据库中的数据排序为可折叠的引导程序 4 卡]
- flutter - 导航到下一个屏幕时如何避免键盘弹出?