Skip to main content
 首页 » 编程设计

Python json.dumps 将空字符串转换为 null

2024年10月24日25qq号

我有一个 Python 模块,其中包含我正在初始化的 Person 对象

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

然后我尝试填充这些字段,如果我无法获得我想要的值,我会返回到默认的空字符串。然后我发布对象:

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

另一方面,我正在使用一个收集人员的 ASP.NET web api,我发现应该为空字符串的项目为 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 
} 

我做错了什么?我想在 python 模块中发送空字符串,而不是空值。我已经测试过使用 ASP.NET 客户端发布到相同的 api,并且在该实例中正确地遇到了空字符串。

请您参考如下方法:

json 工作正常。只是 urllib 有一个非常困惑、冗长且完全不直观的界面。以下是使用 urllib 提交这些数据参数的方法:

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

但实际上,您应该立即摆脱 urllib 并开始使用 requests

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

或

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