Basic
Basic

Reputation: 26766

Custom Json (de)serialisation?

I'm porting some code from .Net to python.

At one point, we need to translate arbitrarily complex json from one format to another.

Eg:

{"Query": 
    {
        "Boolean": {
            "Operator": "And",
            "Parameters": [
                {"Equal": {"Name": "Bob"}},
                {"Boolean": ...}
            ]
        }
    }
}

To...

{"Query": 
    {
        "Left": {"Name":"Bob"},
        "Right": {...},
        "Operator": "And"
    }
}

We were using Json.Net's excellent Newtonsoft.Json.JsonConverter to hook into the serialisation / deserialisation process. We have 2 JsonConverters which convert from the same objects to/from each of these formats.

Public Overrides Function CanConvert(objectType As Type) As Boolean
    Return GetType(QueryDefinition).IsAssignableFrom(objectType)
End Function

This means we can pick out the bits we want to handle manually and allow the stock converter to do all the properties/values that we don't need to treat specially.

Is there any equivalent mechanism/framework in Python? or am I going to have to manually parse every property recursively?

Upvotes: 2

Views: 635

Answers (1)

Sami N
Sami N

Reputation: 1180

You can subclass the default JSONEncoder.

From: http://docs.python.org/2/library/json.html

"To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used."

http://docs.python.org/2/library/json.html#json.JSONEncoder

Example of usage: Custom JSON encoder in Python 2.7 to insert plain JavaScript code

Upvotes: 4

Related Questions