Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

json - Python TypeError: expected string or buffer

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...