Skip to content
Advertisement

Exporting HashMap of HashMap to Python

I have a text parser written in Rust and want to provide a Python interface to it using pyo3.

The parser returns a HashMap within a HashMap and the values of the inner HashMap are of type serde_json::Value. When I try to return this as a PyObject I get an error that I am unable to solve.

This is a minimal exampel of my problem:

JavaScript

Running this results in the error

JavaScript

The goal is to call this function from Python and it returns a dict like this:

JavaScript

Edit: Implemented Solution

(based on the answer of @orlp)

JavaScript

Advertisement

Answer

The problem is that serde_json::Value doesn’t implement the pyo3::conversion::ToPyObject trait. You can’t implement that yourself either, since you can’t implement a foreign trait on a foreign object.

What you can do is wrap your serde_json::Value and implement the trait on that. Something like this should work (untested):

JavaScript

Then you should store MyValues instead.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement