2015-08-19 58 views
1

我試圖找到一種加載JSON對象,然後將鍵映射到Python函數的關鍵字參數的方法。將JSON數據映射到Python關鍵字參數

下面是這種情況的一個例子。

def load_new_category(self, filename): 
    basepath = os.path.dirname(__file__) 
    filepath = os.path.abspath(os.path.join(basepath, "..", "JSON", filename)) 
    with open(filepath) as sample: 
     self.create_new_category(is_active=case['is_active'], 
           description=case['description'], page_title=case['page_title'], 
           meta_keywords=case['meta_keywords'], meta_description=case['meta_description'], 
           navigation_menu=case['navigation_menu'], 
           parent_filter_setting=case['parent_filter_setting'], 
           show_filter=case['show_filter'], sort_filter=case['sort_filter']) 

這種模式在許多函數中都可見,我正在尋找一種推廣到任何JSON文件和函數的方法。也許是裝飾者?

回答

6

這裏只需使用**kwargs語法,因爲你所有的關鍵字參數映射單對一個你的JSON對象鍵:

self.create_new_category(**case)