Artem Malikov
Artem Malikov

Reputation: 215

AttributeError: 'str' object has no attribute 'loads', json.loads()

snippets

    import json
    teststr = '{"user": { "user_id": 2131, "name": "John", "gender": 0,  "thumb_url": "sd", "money": 23, "cash": 2, "material": 5}}'
    json = json.load(teststr)

throws an exception

Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'loads'

How to solve a problem?

Upvotes: 12

Views: 67263

Answers (1)

Sunny Patel
Sunny Patel

Reputation: 8076

json.load takes in a file pointer, and you're passing in a string. You probably meant to use json.loads which takes in a string as its first parameter.

Secondly, when you import json, you should take care to not overwrite it, unless it's completely intentional: json = json.load(teststr) <-- Bad. This overrides the module that you have just imported, making any future calls to the module actually function calls to the dict that was created.

To fix this, you can use another variable once loaded:

import json
teststr = '{"user": { "user_id": 2131, "name": "John", "gender": 0,  "thumb_url": "sd", "money": 23, "cash": 2, "material": 5}}'
json_obj = json.loads(teststr)

OR you can change the module name you're importing

import json as JSON
teststr = '{"user": { "user_id": 2131, "name": "John", "gender": 0,  "thumb_url": "sd", "money": 23, "cash": 2, "material": 5}}'
json = JSON.loads(teststr)

OR you can specifically import which functions you want to use from the module

from json import loads
teststr = '{"user": { "user_id": 2131, "name": "John", "gender": 0,  "thumb_url": "sd", "money": 23, "cash": 2, "material": 5}}'
json = loads(teststr)

Upvotes: 35

Related Questions