Error serializing class instance into json in 8.0.14

I am trying to serialize a python class into json, and it works fine and great in python 2.7 and 3.8

But when I try to test it out in the script console it shows an issue with the stringmap type containing the __dict__ method. I dont see the same issue in any regular python interpreter, so I am curious if this is a Jython issue and something I am potentially missing.

import json

class Operation():
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return json.dumps(operation, default=ComplexEncoder)

def ComplexEncoder(obj):
	print('Encoding the json...')
	return obj.__dict__

operation = Operation("Part 1: Base")

#Encode the operation object into a json
jsonStr = json.dumps(operation, default=ComplexEncoder)

print("Encoded JSON:",jsonStr)

What else is interesting, is in Jython it actually runs the encoder function twice for some reason, printing “Encoding the json…” twice? Whereas in regular python it only runs the function once.

Any ideas would be greatly appreciated!

EDIT: To clarify, it runs the ComplexEncoder method twice even when I comment out the __repr__ method and the line printing at the end like so:

import json

class Operation():
    def __init__(self, name):
        self.name = name

#    def __repr__(self):
#        return json.dumps(operation, default=ComplexEncoder)

def ComplexEncoder(obj):
	print('Encoding the json...')
	return obj.__dict__

operation = Operation("Part 1: Base")

#Encode the operation object into a json
jsonStr = json.dumps(operation, default=ComplexEncoder)

#print("Encoded JSON:",jsonStr)

https://docs.python.org/2/library/json.html

New in version 2.6.

The json module doesn't exist in version 2.5. Not sure where you got your json import from.

Weird I didn’t add it or anything? Any chance ignition is pre-packaging it to help with some things like system.util.jsonEncode or jsonDecode?

Which version are you using? On a 7.9.4 I was using, it gave an error. While that version does already have jsonEncode and jsonDecode system functions.

I was using 8.0.14, good call normal i put that in my intro and forgot.

Ah, in that case, you’re even running Jython 2.7. And my remarks don’t count.

It’s running twice because your encoder is being called to serialize the dict returned by obj.__dict__ after the first call. I’ll have to chalk that up to a problem with Jython - while Python’s json.dumps is a pretty awful API for writing a serialization mechanism (in my humble opinion), it’s certainly able to handle this simple case.

If you only need to serialize domain-specific objects, it should be too bad to essentially write your own traversal scheme that takes an input object, walks down its members, and returns a plain Python structure that can be passed to system.util.jsonEncode as @Sanderd17 suggested.