Convert String (Json Array) to List

I am trying to read Json from a file and not convert to a list. But I get an error when running the Json.load () code. I could not understand. Thank.

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'
+4
source share
2 answers

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

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

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

with open("1.txt") as contactFile:
    data = json.loads(contactFile.read())
+5
source

json.loadtakes a file as an object as the first parameter. So it was supposed to be

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

Source: https://habr.com/ru/post/1531777/


All Articles