marjun
marjun

Reputation: 726

Append dictionary to json response

I want to append dictionary to json response output

JSON response output:

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

Dictionary to append:

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

Expected 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. Is there anyway we can add dictionary to json?

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

Upvotes: 0

Views: 630

Answers (2)

Booboo
Booboo

Reputation: 44043

Your json_response, notwithstanding its name, is a dictionary and not a json representation of a dictionary, which would be a string. But that's fine. You new_dict is an attempt to be a json string, but it is ill-formed. 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:

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

Upvotes: 1

ExplodingGayFish
ExplodingGayFish

Reputation: 2897

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:

import json
new_dict = json.load(new_dict)

Upvotes: 0

Related Questions