16

Need help. Have a list of data named arglist, example: ['dlink', 'des', '1210', 'c', 24] <-- this what "print" views.

And this code:

sw_info ={"Brand":arglist[0],
        "Model":arglist[1],
        "Hardware":arglist[2],
        "Software":arglist[3],
        "Portsnum":arglist[4]}


print json.dumps(sw_info, open("test", "w"))
z = json.loads(open("test", "r"))
print s

It gives:

Traceback (most recent call last):
  File "parsetest.py", line 34, in <module>
    z = json.loads(open("test", "r"))
  File "/usr/lib64/python2.6/site-packages/simplejson/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.6/site-packages/simplejson/decoder.py", line 335, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

Whats wrong?

3
  • 1
    You're trying to loads a file object, not a string. You should just use json.load and json.dump if you want to work with files instead of strings. Commented Oct 25, 2015 at 23:14
  • 3
    First rule of debugging is to assume the error is telling you the literal truth. It's expecting a string but you're not giving it one. So start your investigation with why you're passing something that's not a string or why you're using a function that requires a string when you have something else. Commented Oct 25, 2015 at 23:44
  • You right. So obvious. Thanks for help. Commented Oct 27, 2015 at 16:13

1 Answer 1

33

You are trying to load a file object, when json.loads expects a string. You could either use

z = json.loads(open("test", "r").read())

or, much better:

with open("test") as f:
    z = json.load(f)

In the first example, the file is opened, but never closed (bad practice). In the second example, the context manager closes the file after leaving the context block.

Sign up to request clarification or add additional context in comments.

3 Comments

.read() is important here. The open build-in returns a file object, not a string.
To clarify: json.loads(open(...).read()) works, and json.load(open(...)) also works. loads with an s requires a string, load without s takes a file. .read() turns a file into a string.
@Jonathan No, that would be loads. load expects a file-like object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.