2

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Do you have an example of that in use? ... That was fast thanks. I'll accept when the timeout's up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.