Search code examples
pythonjsonpython-requestsmarklogic

Loading JSON using Python Requests wrong type


I'm trying to load some data to ML using Python. This works ok but the type is set to 'T' and not to 'J' within ML. I'd like to resolve this. The header setting seems to be just for show so how do I do this?

# Sending data
data = {'meting': '477', 'bericht': '473', 'plant': '01'}
url = 'http://server:8000/v1/documents?database=thijsPlantjes&extension=json'
headers = {'Content-Type': 'application/json'}
r = requests.post(url, json = json.dumps(data), auth=HTTPDigestAuth('plantje', 'password'), headers = headers) 

Solution

  • If you use json parameter, requests will serialize for you, so you don't need to json.dumps yourself.

    And it will also set content-type for you; you can drop headers keyword argument.

    r = requests.post(url, json=data, auth=HTTPDigestAuth('plantje', 'password'))
    

    According to requests documentation:

    Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically: