python – TypeError:不是JSON可序列化的

python – TypeError:不是JSON可序列化的,第1张

概述我正在尝试通过“httplib.HTTPSConnection”连接到这个网站“ android-review.googlesource.com”,这实际上是Gerrit(用于审查代码的工具),Gerrit API提供了 JSON格式的审阅数据的接口.我需要收集JSON数据.您可以在此处找到有关Gerrit的更多信息: https://gerritreview.googlesource.com/D 我正在尝试通过“httplib.httpSConnection”连接到这个网站“ android-revIEw.Googlesource.com”,这实际上是Gerrit(用于审查代码的工具),Gerrit API提供了 JSON格式的审阅数据的接口.我需要收集JsON数据.您可以在此处找到有关Gerrit的更多信息: https://gerritreview.googlesource.com/Documentation/rest-api.html

让我解释一下源代码.有一个名为“GetRequestOrCached”的函数将数据保存在文件中以供缓存使用,另一个函数“MakeRequest”创建与网站的连接并返回响应.但是错误与Json.dumps用于请求(req)的部分有关,该请求是字典.

这是错误:

TypeError: <built-in function ID> is not JsON serializable

这是代码:

import socket,sysimport httplibimport pyodbcimport Jsonimport typesimport datetimeimport urllib2import osimport loggingimport re,timedef GetRequestOrCached( url,method,data,filename):  path = os.path.join("Json",filename)  if not os.path.exists(path):    data = MakeRequest(url,data)    time.sleep(1)    data = data.replace(")]}'","")    f = open(path,"w")    f.write(data)    f.close()    return open(path).read()def MakeRequest(url,port=443):  successful = False  while not successful:    try:      conn = httplib.httpSConnection("androID-revIEw.Googlesource.com",port)      headers = {"Accept": "application/Json,application/Jsonrequest","Content-Type": "application/Json; charset=UTF-8","Content-Length": len(data)}      conn.request(method,url,headers)      conn.set_deBUGlevel(1)      successful = True    except socket.error as err:        # this means a socket timeout      if err.errno != 10060:        raise(err)      else:        print err.errno,str(err)        print "sleep for 1 minute before retrying"        time.sleep(60)  resp = conn.getresponse()  if resp.status != 200:    raise GerritDataException("Got status code %d for request to %s" % (resp.status,url))  return resp.read()#-------------------------------------------------filename = "%d-ChangeDetails.Json"url = "/gerrit_ui/rpc/ChangeDetailService"req = {"Jsonrpc" : "2.0","method": "changeDetail","params": [{"ID": ID}],"ID": 44      }data = GetRequestOrCached(url,"POST",Json.dumps(req),filename)print Json.loads(data)

该行导致错误“data = GetRequestOrCached(url,”POST“,filename)”.
如果修复错误的人也检查网站的响应是错误还是正确的响应,我将不胜感激.

解决方法 错误消息说明了一切 – 您的req字典中有 id函数:

req = {"Jsonrpc" : "2.0",#                    ^- here  "ID": 44}

函数不是Json可序列化的,所以这就是你得到错误的原因.

另一方面 – 如果你想传递一个变量,你在使用它之前就没有初始化它.避免使用builtins的名称作为变量名(如ID,int,…)来避免这种问题.

总结

以上是内存溢出为你收集整理的python – TypeError:不是JSON可序列化的全部内容,希望文章能够帮你解决python – TypeError:不是JSON可序列化的所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1193148.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存