2016-02-20 52 views
1

我有Django的兩款車型,我從我的Json得到輸出:如何合併這兩個Jsons?

模型(簡體)

class ServiceSubCategory(models.Model): 
    service_category = models.ForeignKey(ServiceCategory) 
    name_fa = models.CharField(default='', max_length=200) 
    name_en = models.CharField(default='', max_length=200) 

    def __unicode__(self): 
     return self.service_category.name_fa+' -> '+ self.name_fa 

class Service(models.Model): 
    service_sub_category = models.ForeignKey(ServiceSubCategory) 
    img_fa = models.ImageField(default='img/default_service.png',upload_to='img/service/') 
    caption_fa = models.CharField(default='',max_length=200) 
    caption_en = models.CharField(default='',max_length=200) 

    def as_json(self): 
     return { 
       'id': self.id, 
       'caption_fa': self.caption_fa, 
       'caption_en': self.caption_en, 
       'img_fa': unicode(self.img_fa), 
     } 

我想要得到的第一個模型主鍵值並用JSON進行合併

我從ServiceSubCategory得到這個JSON:

[1,2,3,4,5,6,7,8,9,10] 
我是從第二個模型得到

通過運行此代碼:

idJson=json.dumps(list(ServiceSubCategory.objects.values_list('id',flat=True))) 

並獲得此JSON:

[{"caption_fa": "some value", "caption_en": "something", "id": 2, "img_fa": "img/default_service.png"}, 
{"caption_fa": "somthing", "caption_en": "somthing", "id": 1, "img_fa": "img/service/IMAG0099_1H3sdjX.jpg"}] 

通過這個

cat = ServiceSubCategory.objects.get(id=1) 
dictionary=[obj.as_json() for obj in Service.objects.filter(service_sub_category=cat)] 

我想是要合併這兩個JSons得到的東西是這樣的:

[["1":{"caption_fa": "some value", "caption_en": "something", "id": 2, "img_fa": "img/default_service.png"}, 
{"caption_fa": "somthing", "caption_en": "somthing", "id": 1, "img_fa": "img/service/IMAG0099_1H3sdjX.jpg"}], 
["2":{"caption_fa": "some value", "caption_en": "something", "id": 3, "img_fa": "img/default_service.png"}, 
{"caption_fa": "somthing", "caption_en": "somthing", "id": 4, "img_fa": "img/service/IMAG0099_1H3sdjX.jpg"}]] 

這是我正在努力做到這一點:

def service(request): 
    idList=ServiceSubCategory.objects.values_list('id',flat=True) 

    idJson=json.dumps(list(ServiceSubCategory.objects.values_list('id',flat=True))) 
     for i in idList: 
      dictionary=[obj.as_json() for obj in Service.objects.filter(service_sub_category=i)] 
      idJson[i].append(dictionary) #Error 
    return HttpResponse(idJson, content_type='application/json') 

而且我在idJson[i].append(dictionary)收到錯誤:

'海峽' 對象有沒有屬性 '追加'

我真的不知道我該怎麼做。任何幫助,將不勝感激。

回答

0

所以,而不是兩個JSONs,我轉換福斯特陣列一個字符串數組(["1","2","3",...]),並使用zip我合併兩個陣列,然後將其轉換爲一個JSON:

idArray='["1","2","3",...]' 
dictionaries='[[{"caption_fa": "some value", "caption_en": "something", "id": 2}, 
{"caption_fa": "somthing", "caption_en": "somthing", "id": 1}], 
[{"caption_fa": "some value", "caption_en": "something", "id": 3}, 
{"caption_fa": "somthing", "caption_en": "somthing", "id": 4}]]' 
import json 
theArray = dict(zip(idArray, dictionaries)) 
theJson = json.dumps(theArray) 

,其結果是:

[["1":{"caption_fa": "some value", "caption_en": "something", "id": 2}, 
    {"caption_fa": "somthing", "caption_en": "somthing", "id": 1}], 
    ["2":{"caption_fa": "some value", "caption_en": "something", "id": 3}, 
    {"caption_fa": "somthing", "caption_en": "somthing", "id": 4}]] 
+0

無論您在這裏打印的結果如何,在Python中的語句。只需複製粘貼到您選擇的python shell中,您將會看到 – bmbigbang

+0

@bmbigbang我已經測試過並得到了我的答案。 –

0

看起來你有一個字典列表和一個鍵列表,並且想用第二個列表中的鍵創建一個字典詞典。 這裏是這樣做的一些簡化的示例(假設兩個您的列表具有相同的長度):

ids = [1, 2, 3, 4] 
dicts = [{'a':'b'}, {'c':'d'}, {'e':'f'}, {'g':'h'}] 
dict_of_dicts = {i:d for i, d in zip(ids, dicts)} 
print dict_of_dicts 
#{1: {'a': 'b'}, 2: {'c': 'd'}, 3: {'e': 'f'}, 4: {'g': 'h'}} 
+0

它實際上並沒有返回你的答案建議。我得到空格和逗號而不是數字輸出JSON –

0

所以在當前的定義有問題與:

idJson=json.dumps(list(ServiceSubCategory.objects.values_list('id',flat=True))) 

它返回一個陣列,但你想這是你的新字典按我的理解,所以用

idJson={i:[] for i in list(ServiceSubCategory.objects.values_list('id',flat=True))} 

替換這個allthough是公平的實現greenwolf的建議看起來更好該計劃的優雅

編輯** 你最終的結果應該是這個樣子:

def service(request): 
    idList = list(ServiceSubCategory.objects.values_list('id',flat=True)) 
    idJson = {i:[] for i in idList} 
    for i in idJson: 
     cat = ServiceSubCategory.objects.get(id=i) 
     dictionary=[obj.as_json() for obj in Service.objects.filter(service_sub_category=cat)] 
     idJson[i].append(dictionary) 
    return HttpResponse(idJson, content_type='application/json') 

在你的榜樣,你的陣列有一個鍵:值對,然後又字典沒有鑰匙。這是不允許的。數組可以有任何對象,但只有整數作爲鍵。對於key:value對,字典可以具有任何可哈希對象作爲鍵和任何其他類型的值。所以你的選擇是要麼使用數組,其中索引號直接涉及項目編號:

[dict1,dict2,dict3, etc..] 

其中字典(ID)看起來像你的類型的字典之一:

{"caption_fa": "some value", "caption_en": "something", "id": 2, "img_fa": "img/default_service.png"} 

它甚至可以是類型的字典列表:

[[dict1,dict3],[dict2,dict4]] 

,或者您可以使用類型的字典的建議:

{'1': [dict1,dict2], '2': [dict3,dict4]} 
+0

這會返回'{「1」:[],「2」:[],「3」:[],「4」:[],「5」:[ ],「6」:[],「7」:[],「8」:[],「9」:[],「10」:[]}' –