[英]Append dictionary to json response
我想 append 字典到 json 響應 output
JSON 響應 output:
json_response= {
"payload": [
{
"type": "type1",
"id": "0001",
"code": "TWBE",
"version": "20190719",
"creationDate": "20190719"
}]
}
字典到 append:
new_dict = '{"metadata": { "version": 1,,"service": "web-client","module": "Catalog","occurredAt": "2019-09-06T12:56:19.627+02:00"}}'
預期 output:
{
"metadata": { "version": 1,"service": "web-client","module": "Catalog","occurredAt": "2019-09-06T12:56:19.627+02:00"},
"payload": [
{
"type": "type1",
"id": "0001",
"code": "TWBE",
"version": "20190719",
"creationDate": "20190719"
}]
}
我嘗試將 dict 轉換為列表並附加字典,但我希望 output 作為字典。 無論如何我們可以將字典添加到 json 嗎?
if type(json_response) is dict:
json_response = [json_response]
json_response.append(new_dict)
您的json_response
,盡管它的名稱,是一個字典,而不是字典的 json 表示,這將是一個字符串。 但這沒關系。 您new_dict
試圖成為 json 字符串,但它的格式不正確。 最好將它作為字典:
json_response= {
"payload": [
{
"type": "type1",
"id": "0001",
"code": "TWBE",
"version": "20190719",
"creationDate": "20190719"
}]
}
new_dict = {"metadata": {"version": 1, "service": "web-client", "module": "Catalog", "occurredAt": "2019-09-06T12:56:19.627+02:00"}}
# "append" by merging keys:
json_response["metadata"] = new_dict["metadata"]
上面的代碼是通過合並鍵來組合兩個字典。 如果您關心鍵的順序,這是為 Python 3.6 及更高版本中的普通字典維護的,那么:
d = {}
d["metadata"] = new_dict["metadata"]
d["payload"] = json_response["payload"]
嘗試這個:
json_response.update(new_dict)
如果new_dict
是您示例中的字符串,則可能需要先將其轉換為 dict :
import json
new_dict = json.load(new_dict)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.