StackOverflowError on jsonEncode of dict containing Dataset

I need to persist some objects into my database and the quickest way seemed to be to convert them to JSON, then save that. That works ok with a Dataset, but fails on an object that contains a Dataset.

d = system.dataset.toDataset(["foo"], [[1]])
print system.util.jsonEncode(d)
# {"columns":[{"name":"foo","type":"java.lang.Integer"}],"rows":[[1]]}

d2 = {"myDataset": d}
print system.util.jsonEncode(d2)
# RuntimeError: maximum recursion depth exceeded (Java StackOverflowError)

d3 = {"myDataset": system.dataset.toPyDataSet(d)}
print system.util.jsonEncode(d3)
# RuntimeError: maximum recursion depth exceeded (Java StackOverflowError)

Python's json.dumps also fails, even on the basic Dataset. Java's jackson returns a similar error to jsonEncode.

I'm surprised I couldn't find anything else on the forum about this. Does anyone have a workaround, or do I have to convert all the Datasets to Python dicts/lists myself first?

Relevant thread. Looks like encoding the dataset first may work.

I can’t remember when it changed but a Dataset is now also interchangeable with a pyDataset.
Encode the dataset then add it to the dict as json, then it should work.
I believe the conversion may not work correctly unless it can detect the Dataset type directly.

That happened when the version 8.1.x jumped to 8.3.x.

If on 8.3 and below, this does not apply.

Link to change