简体   繁体   English

Append 字典到 json 响应

[英]Append dictionary to json response

I want to append dictionary to json response output我想 append 字典到 json 响应 output

JSON response output: JSON 响应 output:

json_response= {
        "payload": [
            {
                "type": "type1",
                "id": "0001",
                "code": "TWBE",
                "version": "20190719",
                "creationDate": "20190719"
            }]
    }

Dictionary to append:字典到 append:

new_dict = '{"metadata": { "version": 1,,"service": "web-client","module": "Catalog","occurredAt": "2019-09-06T12:56:19.627+02:00"}}'

Expected output:预期 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"
             }]
}

I tried converting dict to list and appended the dictionary, but I want the output as dictionary.我尝试将 dict 转换为列表并附加字典,但我希望 output 作为字典。 Is there anyway we can add dictionary to json?无论如何我们可以将字典添加到 json 吗?

   if type(json_response) is dict:
        json_response = [json_response]
    json_response.append(new_dict)

Your json_response , notwithstanding its name, is a dictionary and not a json representation of a dictionary, which would be a string.您的json_response ,尽管它的名称,是一个字典,而不是字典的 json 表示,这将是一个字符串。 But that's fine.但这没关系。 You new_dict is an attempt to be a json string, but it is ill-formed.new_dict试图成为 json 字符串,但它的格式不正确。 It is better to just have it as a dictionary:最好将它作为字典:

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"]

The above code is combining the two dictionaries by merging keys.上面的代码是通过合并键来组合两个字典。 If you care about the order of the keys, which is maintained for ordinary dictionaries in Python 3.6 and greater, then:如果您关心键的顺序,这是为 Python 3.6 及更高版本中的普通字典维护的,那么:

d = {}
d["metadata"] = new_dict["metadata"]
d["payload"] = json_response["payload"]

Try this:尝试这个:

json_response.update(new_dict)

if new_dict is a string like in your example, you may need to convert it to dict first:如果new_dict是您示例中的字符串,则可能需要先将其转换为 dict :

import json
new_dict = json.load(new_dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM