[英]Insert values from a json list of dicts containing the same keys for two different values in the list of dicts to a MYSQL database
我有一個存儲在json file1中的字典列表,這些字典具有相同的鍵,但每個重復的鍵具有兩個不同的值,如下所示。 我想插入鍵匹配某個列的MySQL數據庫中,然后在從另一個json文件中獲取鍵之后,將兩個值插入到x和y列中。 這是因為我試圖更新從json文件2創建的表,使其包含來自json file1的字典列表中的其他值。
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數據庫中:Key | value one | 在另一個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() """
加載整個文件。 然后循環json2鍵,如果pk在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
您必須在json file1
寫入2個循環
一定像
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.