4

I'm trying to read Json from a file, than convert to list.But i'm getting error at the beginnig of code, Json.load(). I couldn't figure out. Thanks.

import json

with open("1.txt") as contactFile:
    data=json.load(contactFile.read())

1.txt:

[{"no":"0500000","name":"iyte"},{"no":"06000000","name":"iyte2"}]

Error:

  File "/usr/lib/python2.7/json/__init__.py", line 286, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
3
  • 2
    It is better to use open("1.txt", 'r'). Commented Mar 14, 2014 at 14:00
  • 1
    @user2931409: why is that? 'r' is the default. Commented Mar 14, 2014 at 14:02
  • @Martijn Pieters: Oh I didn't know that. IMO because it is more human readable. If you say "it is verbose", I must agree with you. Any upvoter help! Commented Mar 14, 2014 at 14:13

2 Answers 2

6

json.load() works on a file object, not a string. Use

with open("1.txt") as contactFile:
    data = json.load(contactFile)

If you do need to parse a JSON string, use json.loads(). So the following would also work (but is of course not the right way to do it in this case):

with open("1.txt") as contactFile:
    data = json.loads(contactFile.read())
Sign up to request clarification or add additional context in comments.

1 Comment

Thank both of you ( @ thefourtheye and @ Tim Pietzcker ). I misunderstood json load and loads. It works now
4

json.load accepts a file like object as the first parameter. So, it should have been

data = json.load(contactFile)
# [{u'name':u'iyte', u'no': u'0500000'}, {u'name': u'iyte2', u'no': u'06000000'}]

1 Comment

Thank both of you ( @thefourtheye and @Tim Pietzcker ). I misunderstood json load and loads. It works now.

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.