[英]How to merge these two Jsons?
我在Django中有兩個模型,這些模型是從Json輸出的:
型號(簡體)
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)))
並得到這個傑森:
[{"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)
遇到錯誤:
'str'對象沒有屬性'append'
我真的不知道該怎么做。 任何幫助,將不勝感激。
看來您有一個詞典列表和一個鍵列表,並且想要使用第二個列表中的鍵創建一個詞典字典。 這是執行此操作的一些簡化示例(假設兩個列表的長度相同):
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'}}
因此,在您當前的定義中,存在以下問題:
idJson=json.dumps(list(ServiceSubCategory.objects.values_list('id',flat=True)))
它返回一個數組,但據我了解,您希望將此作為您的新字典,所以將其替換為
idJson={i:[] for i in list(ServiceSubCategory.objects.values_list('id',flat=True))}
為了公平起見,實施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對,然后是另一個沒有key的dict。 這是不允許的。 數組可以有任何對象,但只能有整數作為鍵。 對於key:value對,dict可以將任何可哈希對象作為鍵,並將任何其他類型作為值。 因此,您可以選擇使用索引編號直接與項目ID相關的數組:
[dict1,dict2,dict3, etc..]
dict(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]}
因此,我沒有使用兩個JSON,而是將forst數組轉換為字符串數組( ["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}]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.