thebiglebowski11
thebiglebowski11

Reputation: 1461

Python: writing a JSON string to a file.

I have a custom object that I have serialized into JSON data. After the serialization, I write the data back to a JSON file. This seems to be working, however the JSON that I write back to a file is now a string (i.e. it starts with a " and ends with a ").

So when I try to load the new file into be parsed, my parser things that it's a string and I get the error:

 TypeError: string indices must be integers

I serialize the object by doing:

class myEncoder(JSONEncoder):
    def default(self, o):
        return o.__dict__

and then calling this class:

with open('updatedMapData.json', 'w') as outfile:
            json.dump(myEncoder().encode(jsonToEncode) , outfile)

myEncoder().encode(data) returns perfectly, but when it writes, the file is a long string.

How can I solve this issue?

Upvotes: 3

Views: 802

Answers (2)

paulie4
paulie4

Reputation: 502

json.dump's first argument is the object that you want to convert to JSON, but you can pass your class as the cls argument, so you need to call it like this:

json.dump(jsonToEncode, outfile, cls=myEncoder)

Upvotes: 0

ATOzTOA
ATOzTOA

Reputation: 35950

Just do:

outfile.write(myEncoder().encode(jsonToEncode))

Upvotes: 1

Related Questions