繁体   English   中英

如何在javascript中将python类str转换为字典

[英]How can I convert the python class str to dictionary in javascript

我在 python 中有一个这种格式的数据

 d1 = ["id":"hajdgrwe2123", "name":"john law", "age":"95"]

Python 将其作为数据类型“ class 'str' ”。

我正在使用 eel 将数据从 python 发送到 javascript,所以我想将数据转换为 javascript 中的字典,以便我可以在下面进行调用

d1["id"] # 结果应该是 hajdgrwe2123

我尝试在 javascript 中转换为 json 但它没有用。 如何在 javascript 中将 python 类 str 转换为字典?

从 Python 发送到 JS 时,您需要将数据编码为 JSON(例如使用json.dumps() )。

然后,您可以使用以下方法将其解析为 JS 对象:

const d1 = JSON.parse(json_data);

您可以使用以下方法访问它的属性:

d1['id'] // prints: hajdgrwe2123

或者:

d1.id // prints: hajdgrwe2123

您可以使用json.dumps()函数将 Python 对象转换为 JSON 对象字符串:

import json

d1 = {"id":"hajdgrwe2123", "name":"john law", "age":"95"}

json_str = json.dumps(d1)

# json_str = '{"id": "hajdgrwe2123", "name": "john law", "age": "95"}'
# Do something with json_str to pass it to the Javascript process

然后可以按照 domenikk https://stackoverflow.com/a/64424921/14349691 的建议使用 JSON 对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM