首页 > 解决方案 > 将 Python 字典导入 Matlab 结构

问题描述

在将简单的 Python 字典传递到 Matlab 程序的过程中,我遗漏了一些非常基本的东西。我展示的例子被简化为裸露的骨头;我想要的目标远不止于此,但如果我不能让它发挥作用,我对更大的目标就没有希望了。这是与 Matlab 控制台位于同一目录中的文件 demo.py 中的 Python 代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json

def get_demo_map():
    dd = {}
    dd['abc'] = 1
    dd['def'] = 'XYZ'
    dd['mat'] = [[1,2], [3, 4]]
    return json.dumps(dd).__str__()

if __name__ == '__main__':
    print(get_demo_map())

有了这些,这个 Matlab (R2021a) 控制台历史就讲述了整个故事。我读了 JSON 字符串,但 jsondecode() 拒绝它。然后我制作了一个相同的 Matlab 字符串,并且 jsondecode() 符合我的预期。很明显我遗漏了一些东西,看起来我需要将“没有属性的 Python str”转换为正确的 Matlab 字符串。但是怎么做?还是完全是别的东西?

>> dd=py.demo.get_demo_map()

dd = 

  Python str with no properties.

    {"abc": 1, "def": "XYZ", "mat": [[1, 2], [3, 4]]}

>> ddmap = jsondecode(dd)
Error using jsondecode
JSON text must be a character vector or a scalar non-missing string.
 
>> ddstr = '{"abc": 1, "def": "XYZ", "mat": [[1, 2], [3, 4]]}'

ddstr =

    '{"abc": 1, "def": "XYZ", "mat": [[1, 2], [3, 4]]}'

>> ddmap = jsondecode(ddstr)

ddmap = 

  struct with fields:

    abc: 1
    def: 'XYZ'
    mat: [2×2 double]

>> 

标签: pythondictionaryjsondecoder

解决方案


推荐阅读