简体   繁体   English

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

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

I have a data in python that is in this format我在 python 中有一个这种格式的数据

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

Python has it as data type " class 'str' ". Python 将其作为数据类型“ class 'str' ”。

I am sending the data from python to javascript using eel so I want to convert the data to dictionary in javascript so that I can make the call below我正在使用 eel 将数据从 python 发送到 javascript,所以我想将数据转换为 javascript 中的字典,以便我可以在下面进行调用

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

I tried converting to json in javascript but it did not work.我尝试在 javascript 中转换为 json 但它没有用。 How can I convert the python class str to dictionary in javascript?如何在 javascript 中将 python 类 str 转换为字典?

When sending from Python to JS, you need to encode the data as JSON (using json.dumps() for example).从 Python 发送到 JS 时,您需要将数据编码为 JSON(例如使用json.dumps() )。

Then, you can parse it to a JS object using:然后,您可以使用以下方法将其解析为 JS 对象:

const d1 = JSON.parse(json_data);

You can access it's properties using:您可以使用以下方法访问它的属性:

d1['id'] // prints: hajdgrwe2123

or:或者:

d1.id // prints: hajdgrwe2123

You can use json.dumps() function to convert a Python object to a JSON object string:您可以使用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

The JSON object can then be used as suggested by domenikk https://stackoverflow.com/a/64424921/14349691 .然后可以按照 domenikk https://stackoverflow.com/a/64424921/14349691 的建议使用 JSON 对象。

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

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