Home  >  Q&A  >  body text

Convert python json to dictionary and store it in mysql

d={
    "state": "ok",
    "errmsg": "",
    "data": {
               "id": 1,
                "username": '李元霸'
            }
        }
        }
        }
        for i in d['data']:
           conn = pymysql.connect(host='localhost', port=3306, user='root',         passwd='123456', db='test', charset='utf8')
        cursor = conn.cursor()
        tsql = "insert into test1(id,name)values(%s,'%s')" % (i['id'],i['username'])
        print(tsql)
        cursor.execute(tsql)
        conn.commit()
        conn.close()

I can handle this kind of deposit, but I don’t know how to add the key.
How about the following 2017-01-02": {"16777216": { These two keys are stored in mysql

along with the fields id and username.
{
    "state": "ok",
    "errmsg": "",
    "data": {
        "2017-01-02": {
            "16777216": {
               "id": 1,
                "username": '李元霸'
            }
        },
        "2017-01-06": {
            "16777456": {
                "id": 2,
                "username": '陈坤'
            }
        },
    }
}

Dictionary stored in mysql

I have used it

代言代言2675 days ago984

reply all(3)I'll reply

  • 習慣沉默

    習慣沉默2017-06-22 11:53:32

    a={xxxx}

    Do you want this?

    reply
    0
  • 高洛峰

    高洛峰2017-06-22 11:53:32

    d = {
        "state": "ok",
        "errmsg": "",
        "data": {
            "2017-01-02": {
                "16777216": {
                   "id": 1,
                    "username": '李元霸'
                }
            },
            "2017-01-06": {
                "16777456": {
                    "id": 2,
                    "username": '陈坤'
                }
            },
        }
    }
    
    for k, v in d['data'].iteritems():
        number = v.keys()[0]
        print k, number, v[number]['id'], v[number]['username']

    reply
    0
  • 学习ing

    学习ing2017-06-22 11:53:32

    Just use a loop to take out the data you need and insert it into the database
    The following code can only handle the simplest case

    #*--encoding: utf8--*
    
    import json
        
    string = '''{
        "state": "ok",
        "errmsg": "",
        "data": {
            "2017-01-02": {
                "16777216": {
                   "id": 1,
                    "username": "李元霸"
                }
            },
            "2017-01-06": {
                "16777456": {
                    "id": 2,
                    "username": "陈坤"
                }
            }
        }
    }'''
    
    ret  = json.loads(string)
    data = ret['data']
    
    for date in data.keys():
        arr = []
        arr.append(date)
        info = data[date]
        arr.append(info.keys()[0])
        arr.append(info.values()[0]['id'])
        arr.append(info.values()[0]['username'])
        print(arr)
    

    Besides, the json you gave doesn’t seem to be very correct. .
    run code

    reply
    0
  • Cancelreply