Handle invalid fieldnames when parsing python dict to matlab via struct

조회 수: 7 (최근 30일)
I am trying to convert a python dict to a Matlab struct like so:
pyClass = py.someClass.someSubClass();
data = x.someFunction();
data = struct(data);
This usually works fine, however, Matlab throws the following error:
Error using py.dict/struct
Invalid field name "yyy/xxx"
I know that Matlab requires the following three conditions for fieldnames to be valid:
start with a letter, otherwise assigning to that field will error
contain only letters, numbers, and/or the underscore character, otherwise assigning to that field will error,
and must be no longer than namelengthmax (currently 63) characters, otherwise you will receive a warning and the field name will be truncated
Does anyone know how I can handle this error - i.e. have a small python function that I can call from within Matlab to remove invalid characters?
Here is a snippet of what the python dict looks like (in this case the "/" is the issue):
data =
Python dict with no properties.
{'BTC/USD': {'fee_loaded': False, 'percentage': True, 'tierBased': True, 'maker': 0.001, 'taker': 0.002, 'tiers': {'taker': [[0, 0.002], ...
Thanks in advance!

채택된 답변

Benvaulter
Benvaulter 2018년 5월 8일
I solved the issue by coverting the dict within python to json and then outputting the json to matlab where I then decode the data to retrieve the final struct which works perfectly fine for me so far. Here is the solution that I came up with:
pyClass = py.someClass.someSubClass();
data = x.someFunction();
data = py.json.dumps(data);
data = char(data);
data = jsondecode(data);
  댓글 수: 1
Rik
Rik 2018년 5월 8일
If this indeed solves your problem, you can mark this as accepted answer

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2018년 5월 8일
If you can get a list of the names in your dict object that you want to be the fieldnames in the MATLAB struct array, pass them through matlab.lang.makeValidName.
  댓글 수: 1
Martin Ryba
Martin Ryba 2024년 9월 1일
편집: Martin Ryba 2024년 9월 1일
So, it would be very handy if there was flag to the struct() function to do this. I can't use the JSON hack as dumps() is erroring on "Object of type MaskedArray is not JSON serializable". Is there a sample script as to how we extract the names from the dict, clean them up, and then pass the right pieces into struct()? Otherwise, I'm stuck.
Follow-up: I found I could use the dict object's get() method to retrieve just the keys I wanted and avoid the unwanted one with the bad name:
dat = radar.fields.get('reflectivity'); % Retrieve reflectivity from dict of dicts
data = double(dat.get('data')); % Pull the data and convert numpy MaskedArray to double

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by