簡體   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