Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String (Json Array) to List

Tags:

python

json

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'
like image 873
ridvanzoro Avatar asked Jan 11 '23 00:01

ridvanzoro


2 Answers

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())
like image 153
Tim Pietzcker Avatar answered Jan 23 '23 10:01

Tim Pietzcker


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'}]
like image 31
thefourtheye Avatar answered Jan 23 '23 12:01

thefourtheye