Search code examples
mysqljsonjson-extract

Convert json string to rows in mysql


How can I convert this json string to a mysql row in 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}

Is there any solution for this?


Solution

  • Based on your comments, it sound like this is what you want to do:

    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()