Alex
Alex

Reputation: 25

Convert Python dictionary to a JSON array

Here's my function which connects to an API:

def order_summary():
    """Get order summary for a specific order"""
    # Oauth2 params
    headerKey = api_login()
    headers = {'Authorization': headerKey}

    # Payload params
    payloadOrderSum = {
        "domainId": 15,
        "domainName": "SGL",
        "orderId": 3018361
    }

    # API response
    orderSumResp = requests.post(url + "order/summary", data=payloadOrderSum, headers=headers)
    print(orderSumResp.content)

The API expects a JSON array as Payload Params which essentially looks like that:

[
  {
    "domainId": 0,
    "domainName": "string",
    "orderId": 0
  }
]

The other endpoints I coded for on this API didn't need for the params to be an array so I could just use them as is and send them as a dictionary and it worked.

I've tried a couple things using the JSON library but I can't seem to get it to work. I saw that the JSonEncoder converts lists and tuples to JSON arrays but I couldn't figure it out.

Not sure what other info I could provide but just ask if there are any.

Thanks!

Upvotes: 1

Views: 699

Answers (3)

Tor Stava
Tor Stava

Reputation: 321

It could help if you specify what you tried with the JSON library.

However, you might wanna try this if you haven't already done so:

import json
payloadOrderSum = json.dumps(
    {
    "domainId": 15,
    "domainName": "SGL",
    "orderId": 3018361
    }
)

Upvotes: 0

hoefling
hoefling

Reputation: 66181

Wrap payloadOrderSum into a list:

payloadOrderSum = {
    "domainId": 15,
    "domainName": "SGL",
    "orderId": 3018361
}

orderSumResp = requests.post(url + "order/summary", json=[payloadOrderSum], headers=headers)

Note that I used json kwarg instead of data (added in version 2.4.2).

Upvotes: 4

mtt2p
mtt2p

Reputation: 1906

dump your dict with json.dumps requests-doc

r = requests.post(url, data=json.dumps(payload))

Upvotes: 0

Related Questions