python json轉字典存入mysql
代言
代言 2017-06-22 11:51:32
0
3
986
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()

這種我會處理存入但是加key就不知道了
怎麼吧下面的2017-01-02": {"16777216": {這2個key和字段id,username一起存入mysql

##

{
    "state": "ok",
    "errmsg": "",
    "data": {
        "2017-01-02": {
            "16777216": {
               "id": 1,
                "username": '李元霸'
            }
        },
        "2017-01-06": {
            "16777456": {
                "id": 2,
                "username": '陈坤'
            }
        },
    }
}
字典存入mysql

##### ###我使用過###
代言
代言

全部回覆(3)
習慣沉默

a={xxxx}

是想要這種嗎?

小葫芦

雷雷

学习ing

用循環將你需要的資料取出然後插入到資料庫就行了
下面的程式碼只能處理最簡單的情況

#*--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)

此外,你給的json似乎不太正確。 。
run code

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!