Python调用Bitcoin RPC接口时遭遇TypeError: the JSON object must be str, bytes or bytearray, not NoneType错误的求助
排查与解决TypeError: the JSON object must be str, bytes or bytearray, not NoneType错误
嘿,这个错误的根源其实很明显——你的getinfo()函数根本没返回数据!让我一步步给你拆解问题,然后搞定它:
错误核心原因
你写的getinfo()函数里,只做了print(rpc_connection.getinfo()),没有加return语句。Python里如果函数没有显式返回值,默认会返回None。当你执行json.loads(getinfo())时,本质上是在把None传给json.loads(),而这个函数只接受字符串、字节这类能解析成JSON的类型,自然就抛出类型错误了。
第一步:修复getinfo(),让它返回RPC数据
把函数改成下面这样,先获取数据、打印,然后返回给调用者:
def getinfo(): rpc_connection = AuthServiceProxy("http://%s:%s@127.0.0.1:22225"%("user", "pass")) node_info = rpc_connection.getinfo() print(node_info) return node_info
第二步:删掉多余的JSON来回转换
你后面写的这些代码完全是冗余的:
data = json.loads(getinfo()) jtopy=json.dumps(data) dict_json=json.loads(jtopy)
因为AuthServiceProxy的getinfo()方法会直接返回Python字典,根本不需要再用json.loads()解析。你这相当于把字典转成JSON字符串,再转回到字典,纯纯的多此一举。
修正后的完整代码
直接用返回的字典提取你要的错误信息就行,看下面的完整代码:
import json import cozmo from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException def getinfo(): # 建议加个异常捕获,防止RPC连接出错 try: rpc_connection = AuthServiceProxy("http://%s:%s@127.0.0.1:22225"%("user", "pass")) node_info = rpc_connection.getinfo() print(node_info) return node_info except JSONRPCException as e: print(f"RPC调用失败: {e}") return None # 获取节点信息字典 node_data = getinfo() if node_data: # 提取目标错误信息,用get方法避免键不存在报错 target_error = node_data.get("errors", "未找到错误信息") print("提取到的错误信息:", target_error) # 如果需要让Cozmo播报,取消下面的注释 # def cozmosay(robot: cozmo.robot.Robot): # robot.say_text(target_error).wait_for_completed() # # cozmo.run_program(cozmosay)
额外提醒
- 确保你的Bitcoin节点RPC服务确实在
127.0.0.1:22225运行,且用户名密码和配置一致,不然会触发RPC异常。 - 用
dict.get("key", 默认值)的方式提取值比直接dict["key"]更安全,避免因为键不存在导致崩溃。
内容的提问来源于stack exchange,提问作者IdotMaster1
相关产品推荐
相关产品推荐

