python - 将 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]
>>
解决方案
推荐阅读
- php - Simplenews 通讯网址?
- java - 在不同时区之间格式化时间的正确方法是什么?
- python - 四舍五入到任何给定值python
- mysql - 如何根据 A 列中的数据将 B 列的 SQL 搜索结果汇总为总和?
- scala - 高阶函数
- javascript - 使用 javascript 使用 RSA 编码的公钥解码 JSON Web 令牌
- scala - Zeppelin:java.lang.NoClassDefFoundError:org/apache/spark/Logging
- php - 数组合并/插入不起作用
- javascript - D3 时间刻度条形图未与 x 轴对齐
- asp.net-mvc - 带有 Angular 的 ASP.NET MVC :- 页面刷新或重新加载会出现 404 错误