簡體   English   中英

Django python:如何從Django queryset制作json

[英]django python: how to make json from django queryset

我有查詢集,它在轉換后的列表后返回一個json字符串。

[{"pid": 1, "loc": "KL", "sid": 1, "sd": "south-1"},
 {"pid": 1, "loc": "KL", "sid": 2, "sd": "north-5"},    
 {"pid": 1, "loc": "KL", "sid": 3, "sd": "west-3"}
]

我已經嘗試了許多序列化器選項,但不知道如何使上述內容成為:

[{"pid": 1,
  "s": [{"sid": 1, "sd": "south-1",
         "sid": 2, "sd": "north-5",
         "sid": 3, "sd": "west-3"
       }]
}]

首先,您的預期輸出中有錯誤。 您可能的意思是:

[{"pid": 1,
  "s": [{"sid": 1, "sd": "south-1"},
        {"sid": 2, "sd": "north-5"},
        {"sid": 3, "sd": "west-3"}
       ],
  "loc": "KL"
}]

s應該是字典列表,而不是一個字典(和沖突鍵)。 我添加了"loc": "KL"因為它似乎丟失了。

假設每個查詢只返回相同的pidloc ,你可以創建s與每個列表sidsd在原來的查詢:

>>> q = ... # as above
>>> r = {"pid": q[0]["pid"], "loc": q[0]["loc"]}  # since pid and loc are always the same
>>> r["s"] = [{"sid": x["sid"], "sd": x["sd"]} for x in q]
>>> print r
[{'pid': 1,
  's': [{'sid': 1, 'sd': 'south-1'},
        {'sid': 2, 'sd': 'north-5'},
        {'sid': 3, 'sd': 'west-3'}
       ],
  'loc': 'KL'
}]
>>> print json.dumps(r)  # gives the output as a json string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM