2014-09-04 63 views
1

我有一個列表存儲在一個json文件1中有相同的鍵,但每個重複有兩個不同的值鍵如下所示。我想插入一個MySQL數據庫,其中鍵匹配某個列,然後在從另一個json文件2獲取密鑰後,將這兩個值插入到列x和y中。這是因爲我一個嘗試更新從JSON文件2創建一個表,包含從JSON從http://stardict.sourceforge.net/Dictionaries.php下載列表附加值文件1插入從一個包含相同鍵的字符串json列表中的值到列表中的兩個不同的值到一個MYSQL數據庫

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() """ 
+0

你有什麼解決方案的字典? – Nilesh 2014-09-04 04:16:40

+1

現在讓我們直接添加吧 – Mover 2014-09-04 04:22:44

+0

還不清楚哪些不起作用?請在沒有工作的地方給出問題陳述 – Nilesh 2014-09-04 04:36:01

回答

1

加載整個文件。然後循環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 
0

你必須寫2路在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 
相關問題