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

我正在尝试通过“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, sys
import httplib
import pyodbc
import json
import types
import datetime
import urllib2
import os
import logging
import re, time

def GetRequestOrCached( url, method, data, filename):

  path = os.path.join("json", filename)
  if not os.path.exists(path):
    data = MakeRequest(url, method, data)
    time.sleep(1)
    data = data.replace(")]}'", "")
    f = open(path, "w")
    f.write(data)
    f.close()
    return open(path).read()

def MakeRequest(url, method, data, 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, data, 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“,json.dumps(req),filename)”.
如果修复错误的人也检查网站的响应是错误还是正确的响应,我将不胜感激.

最佳答案 错误消息说明了一切 – 您的req字典中有
id函数:

req = {"jsonrpc" : "2.0", 
  "method": "changeDetail",
  "params": [{"id": id}],
#                    ^- here
  "id": 44
}

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

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

点赞