2

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.

1
  • json.dumps(person) does not convert the empty strings to null. But it would convert None to null. Commented Jan 30, 2016 at 10:40

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.