4

I have the following json file named json.txt with the following data,

{"id":99903727,"nickname":"TEST_MLA_OFF","registration_date":"2010-12-03T14:19:33.000-04:00","country_id":"AR","user_type":"normal","logo":null,"points":0,"site_id":"MLA","permalink":"http://perfil.mercadolibre.com.ar/TEST_MLA_OFF","seller_reputation":{"level_id":null,"power_seller_status":null,"transactions":{"period":"12 months","total":25,"completed":25,"canceled":0,"ratings":{"positive":0,"negative":0,"neutral":1}}},"status":{"site_status":"deactive"}}

I obtained it using wget. I tried to load that json data with python using the following python code,

json_data = json.load('json.txt')
data = json.load(json_data)
json_data.close()

print data

but that throws the following error,

Traceback (most recent call last):
  File "json-example.py", line 28, in <module>
    main()
  File "json-example.py", line 21, in main
    json_data = json.load('json.txt')
  File "/opt/sage-4.6.2-linux-64bit-ubuntu_8.04.4_lts-x86_64-Linux/local/lib/python/json/__init__.py", line 264, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

I couldn't find googling what is the reason of the error.

Best regards.

2 Answers 2

15

Even better practice is to use the with statement.

with open('json.txt', 'r') as json_file:
    data = json.load(json_file)

This makes sure the file gets closed properly without you worrying about it.

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

Comments

9

You need to give json.load a file stream object:

json_file = open('json.txt')
data = json.load(json_file)
json_file.close()

print data

1 Comment

I tried the same on a file containing {"a":1,"b":2} json object and I got the error AttributeError: __exit__. Any help will be useful.

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.