Evonet
Evonet

Reputation: 3640

Python json.dumps converting empty string to null

I have a Python module with a Person object that I'm initialising like this

person = {
    'name': "",
    'city': "",
    'phone1': "",
    'emailaddress': "", 
    }

I then try to populate the fields, counting on falling back to the default empty string if I can't get the values I'm after. I then post the object:

req = urllib2.Request('API_LOCATION')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(person))

On the other side I'm using an ASP.NET web api which collects the person, and I'm finding that the items that should be empty strings are null

[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/postperson")]
public JsonResult PostPerson(Person item)
{
    ... Items that I expect to be empty strings are actually null
}

What am I doing wrong? I'd like to send empty strings in the python module, not nulls. I've tested using an ASP.NET client to post to the same api, and empty string are coming across correctly in that instance.

Upvotes: 2

Views: 1553

Answers (1)

Brendan Abel
Brendan Abel

Reputation: 37539

json is working fine. It's just that urllib has a very confusing, verbose, and completely unintuitive interface. Here's how you would submit those data parameters using urllib:

import urllib
import urllib2

data = urllib.urlencode(person)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)

But really, you should immediately get rid of urllib and start using requests

reponse = requests.get(url, data=person)

or

response = requests.post(url, data=person)

Upvotes: 2

Related Questions