python – ‘dict’对象没有属性’loads’
发布时间:2020-12-20 12:30:14 所属栏目:Python 来源:网络整理
导读:我试图创建一个简单的键/值存储客户端,接受来自这样的文本文件的输入 listset foo barget foolist 这是我得到的错误 Traceback (most recent call last): File "hiringAPIv1.py",line 37,in module json = json.loads(handle.read())AttributeError: 'dict'
我试图创建一个简单的键/值存储客户端,接受来自这样的文本文件的输入
list set foo bar get foo list 这是我得到的错误 Traceback (most recent call last): File "hiringAPIv1.py",line 37,in <module> json = json.loads(handle.read()) AttributeError: 'dict' object has no attribute 'loads' 我目前在for循环中有整个东西为每个新命令调用url,但我遇到任何大于1行的输入文件的问题.这是我的来源,我正在使用Python. import urllib import urllib2 import fileinput import json import pprint urlBase = "http://hiringapi.dev.voxel.net/v1/" f = file('input.txt','r') for line in f: contents = line.split() #print contents #print len(contents) if len(contents) >= 1: command = contents[0] if len(contents) >= 2: key = contents[1] if len(contents) >= 3: value = contents[2] if command == 'get': urlFinal = urlBase + "key?key=" + key output = key if command == 'set': urlfinal = urlBase + "key?key=" + key + "&value=" + value output = 'status' if command =='list': urlFinal = urlBase + command #if command == 'delete': response = urllib2.Request(urlFinal) try: handle = urllib2.urlopen(response) json = json.loads(handle.read()) #pprint.pprint(json) #pprint.pprint(json['status']) if command == 'list': print str(json['keys']) else: print str(json[output]) except IOError,e: if hasattr(e,'code'): print e.code if hasattr(e,'msg'): print e.msg if e.code != 401: print 'We got another error' print e.code else: print e.headers print e.headers['www-authenticate'] f.close() 解决方法
您使用.loads()函数的结果替换了json模块:
json = json.loads(handle.read()) 不要那样做.使用其他名称存储数据.或许使用数据: data = json.loads(handle.read()) if command == 'list': print str(data['keys']) else: print str(data[output]) 请注意,json模块还有一个.load()函数(最后没有s),它接受一个类似文件的对象.你的句柄就是这样一个对象,所以你可以使用json.load()来读取响应: data = json.load(handle) if command == 'list': print str(data['keys']) else: print str(data[output]) 请注意,我只传入句柄,我们不再调用.read(). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |