Kristijan Stefanoski
Kristijan Stefanoski

Reputation: 262

Python json.dump results in 'str' has no attribute 'dump'

I am trying to read a JSON file which contains just an object with one property which is the index. That is successful but when i try to rewrite to the same JSON file i get an error. The code is bellow :

import sys
import json
import os
import os.path
import json
try:
    json_path = path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'indexes', 'table_index.json')
    with open(json_path) as json_file:  
        data = json.load(json_file)
    index1 = 4
    data["index"] = index1

    print(type(data)) #Prints 'dict'
    with open((json_path), 'wb') as f:  
        json.dump(data, f)
except Exception as e: 
     print(e)

The error i get is

'str' object has no attribute 'dump'

What i am basically trying to achieve is read the JSON, change the index property to a different value and at the end rewrite to the same JSON file. Printing data["index"] before writing gives the correct value of 4.

Upvotes: 1

Views: 12686

Answers (1)

Cleb
Cleb

Reputation: 26039

As discussed in the comments, the most likely reason is that you define somewhere in your code a variable called json which shadows the module name. For example,

import json

json_string = '{"something": 4}'
print(json.dumps(json_string))  # prints "{\"something\": 4}"

If you, however, make an assignment like this:

json = '{"something_else": 4}'

and then call the same command as above

print(json.dumps(json_string))

it will raise

AttributeError: 'str' object has no attribute 'dumps'

So, all you have to do is to check in your code whether you made an assignment like this, change it and the issue should be resolved.

Upvotes: 9

Related Questions