将包含相同键的json字典列表中的值插入MYSQL数据库

1 投票
2 回答
583 浏览
提问于 2025-04-19 17:58

我有一个存储在json文件1中的字典列表,这些字典有相同的键,但每个重复的键有两个不同的值,具体如下所示。我想把这些数据插入到MySQL数据库中,条件是键与某个列匹配,然后将这两个值插入到比如说x列和y列中,这个键是从另一个json文件2中获取的。这是因为我想更新一个从json文件2创建的表,使其包含来自json文件1的字典列表中的额外值。

json file 1
[{"a": 0.022222222222162753,      
"b": 0.022222222222162753, 
"c":0.022222222222162753, 
"d": 0.022222222222162753,
"e": 2.6761620240410805e-12, 
"f": 0.022222222222162753},
{"a": 0.022222222222162753, 
"b": 0.022222222222162753, 
"c": 0.022222222222162753, 
"d": 0.022222222222162753, 
"e": 0.022222222222162753,
"f": 0.022222222222162753}]

json file 2
{"a":1,      
"b": 2, 
"c": 3, 
"d": 4,
"e": 5, 
"f": 6}

这是我用来将结果加载到MySQL数据库中的代码,按照一个列匹配重复键的方式,格式是:键|值一|值二,前提是先在另一个json文件中找到这些键。

 for line3 in open("json file 2.json"):
    jline3=json.loads(line3)
    url3 =jline1["url"]

    for line4 in open("json file 1.json"):
        jline4 = json.load(line4)
        computedHITS=jline2[url3]

        """cursor.execute( """
          """  UPDATE `RANKED`.`EVALINDEX`
            SET `HITS`= %s
            WHERE `URL` = %s """
            """,  (computedHITS, url3))"""
        print "Number of rows inserted: %d" % cursor.rowcount
        db.commit() """

2 个回答

0

你需要在json file1里写两个循环。

它的格式应该是这样的:

for json_raw_data in open("json file 2.json"):
    # Load full json data at a time
    json_objects = json.loads(json_raw_data)
    #Loop over each dict in json data.
    for each_date in json_objects:
        #Do your operation
1

先把所有的文件都加载进来。然后遍历json2里的每一个键,如果在json1文件中找到了对应的主键,就进行更新。

>>> import json
>>> with open("file_2.json") as f2, open("file_1.json") as f1:
...     json_pks     = json.loads(f2.read())
...     json_updates = json.loads(f1.read())
...     for pk in json_pks:
...         x_value = json_updates[0].get(pk,'')
...         y_value = json_updates[1].get(pk,'')
...         
...         if x_value and y_value:
...             #db stuff
...             print "update YOUR_TABLE set x=%r,y=%r where YOUR_PK=%s" % (x_value,y_value,pk)
... 
update YOUR_TABLE set x=0.022222222222162753,y=0.022222222222162753 where YOUR_PK=a
update YOUR_TABLE set x=0.022222222222162753,y=0.022222222222162753 where YOUR_PK=c
update YOUR_TABLE set x=0.022222222222162753,y=0.022222222222162753 where YOUR_PK=b
update YOUR_TABLE set x=2.6761620240410805e-12,y=0.022222222222162753 where YOUR_PK=e
update YOUR_TABLE set x=0.022222222222162753,y=0.022222222222162753 where YOUR_PK=d
update YOUR_TABLE set x=0.022222222222162753,y=0.022222222222162753 where YOUR_PK=f

撰写回答