Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'dict' object has no attribute 'loads'

Tags:

python

json

Im trying to create a simple key/value store client that accepts input from a text file like this

list
set foo bar
get foo
list

This is the error I am getting

Traceback (most recent call last):
  File "hiringAPIv1.py", line 37, in <module>
    json = json.loads(handle.read())
AttributeError: 'dict' object has no attribute 'loads'

I currently have the whole thing in a for loop to call the url for each new command but I'm having issues with any input file larger than 1 line. Here is my source, i'm using 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()
like image 849
user2361236 Avatar asked May 08 '13 07:05

user2361236


1 Answers

You replaced your json module with the results of the .loads() function:

json = json.loads(handle.read())

Don't do that. Use a different name to store your data. Use data perhaps:

data = json.loads(handle.read())
if command == 'list':
    print(data['keys'])
else:
    print(data[output])

Note that the json module also has a .load() function (no s at the end) that takes a file-like object. Your handle is such an object, so you can use json.load() instead and have that read the response:

data = json.load(handle)
if command == 'list':
    print(data['keys'])
else:
    print(data[output])

Note that I pass in just the handle, we don't call .read() anymore. I also removed the str() calls; print handles that for us.

like image 162
Martijn Pieters Avatar answered Sep 21 '22 02:09

Martijn Pieters