gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:37 25 4
gpt4 key购买 nike

我有一个 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)

关于Python json.dumps 将空字符串转换为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35100532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com