GoddessAphrael
GoddessAphrael

Reputation: 15

Python JSON serializing issue

I've never used JSON before.

I have file that contains 151 differing pre-defined lists. What I want to do is to be able to read the file, and using a class, create 151 objects from the information stored in the file.

The issue I am having is that I can get the file to read, however, it is not creating the objects. From what I can understand, this is because the file contains both integer and string components in the 151 lists - but the read file is only comprised of strings.

Having found JSON - as I understand it - it can serialize and deserialize the information as both integer and string - thus allowing the Class to create the 151 objects.

However - I am having an issue understanding how JSON works exactly, and, not being familiar with it, I am struggling to understand its error messages also.

The Error received is thus:

Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
json.dump(Compile_Index, r"C:\Users\Aphrael\Desktop\Index.py")
File "C:\Python34\lib\json\__init__.py", line 178, in dump
for chunk in iterable:
File "C:\Python34\lib\json\encoder.py", line 429, in _iterencode
o = _default(o)
File "C:\Python34\lib\json\encoder.py", line 173, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <_io.TextIOWrapper name='C:\\Users\\Aphrael\\Desktop\\Index.py' mode='r+' encoding='cp1252'> is not JSON serializable

Would someone be kind enough either to tell me that I am going about what I am attempting to do incorrectly, and set me on the correct path - or otherwise explain what JSON is trying to tell me is the reason that my data is not serializable?

Upvotes: 0

Views: 7073

Answers (3)

GoddessAphrael
GoddessAphrael

Reputation: 15

Thanks for the advice.

I was able to get it to work, however, I was persuaded by my tutor to do the same thing a different way by placing the information into a .dat file and using the exec() function - enabling the code to be easily transferred to other languages, as well as apparantly being safer regarding executing code that may have been tampered with.

Upvotes: 0

Joao Luiz Cadore
Joao Luiz Cadore

Reputation: 2732

Try to use the code bellow:

json.dumps(objectName.__dict__)

Change objectName for your object.

Upvotes: 0

apex-meme-lord
apex-meme-lord

Reputation: 371

I'm going to take a wild guess since you didn't post your code. You did this:

import json

with open('file.json') as f:
    json.loads(f)

Instead of:

import json

with open('file.json') as f:
    json.loads(f.read())

Upvotes: 4

Related Questions