首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在mysql中将json字符串转换为行

在mysql中将json字符串转换为行
EN

Stack Overflow用户
提问于 2019-06-23 21:36:19
回答 1查看 168关注 0票数 0

如何在mysql中将此json字符串转换为mysql行?

代码语言:javascript
复制
"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}

对此有什么解决方案吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-24 08:46:42

根据你的评论,这听起来就是你想要做的:

代码语言:javascript
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56724408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档