2017-06-14 89 views
0

我有2個json文件! f1.json和f2.json將JSON合併到列表

內容: 「f1.json」

{ 
    "tests": 
    [ 
     {"a": "one", "b": "two"}, 
     {"a": "one", "b": "two"} 
    ] 
} 

內容: 「f2.json」

{ 
    "tests": 
    [ 
     {"c": "three", "d": "four"} 
    ] 
} 

需要的輸出 - 以列表格式

[{a:"one",b:"two"},{a:"one",b:"two"},{c:"three",d:"four"}] 

我以「unicode」格式獲得相同的輸出。 有沒有人有辦法讓它沒有unicode?

我的輸出

[{u'a': u'one', u'b': u'two'}, {u'a': u'one', u'b': u'two'}, {u'c': u'three', u'd': u'four'}] 

代碼:

files=['t1.json','t2.json']  


import json,ast       

empty = []        


for elements in files:   
    fh = open(elements, 'r')    
    filedata = fh.read()     
    fh.close()       
    data = json.loads(filedata)   

    empty.append(data['tests'])   
final = []        
for elements in empty:     
    for dict in elements:     
     final.append(dict)    
print final       
+0

我做編輯更多細節。請看 –

+0

你正在打印一個python列表,所以你的輸出是python列表格式。如果您希望以JSON格式輸出,則應該在打印之前將數據轉換爲JSON:'print json.dumps(final)' – Hamms

+0

相同的輸出!沒有變化 –

回答

0

試試下面的代碼

import json 

l = [] 
files=['t1.json','t2.json'] 
for file in files: 
    with open(file, 'r') as file: 
     d = json.loads(file.read()) 
     l.extend(d["tests"]) 
print l