簡體   English   中英

Python 3 如何將類型列表中的數據轉換回 dict

[英]Python 3 How to convert data in type list back to dict

如何將類型列表中的數據轉換回 dict 如下示例代碼。 謝謝

[{
                        "type": "box",
                        "layout": "horizontal",
                        "margin": "xs",
                        "contents": [
                            {
                                "type": "text",
                                "text": "12/12/2019 time 15:00",
                                "size": "sm",
                                "weight": "bold"
                            },
                            {
                                "type": "text",
                                "text": "Press",
                                "size": "sm",
                                "align": "end",
                                "weight": "bold",
                                "color": "#EE4C4C",
                                "action": {
                                    "type": "message",
                                    "label": "Click",
                                    "text": "to to this"
                                }
                            }
                        ]
                    }]

所以我嘗試轉換回 str 並刪除 "[" , "]" 並轉換回 dict 但當我將其帶到 json.dumps 時,結果顯示不支持格式,如下所示

"{'type': 'box', 'layout': 'horizontal', 'margin': 'xs', 'contents': [{'type': 'text', 'text': '12/12/2019 time 15:00', 'size': 'sm', 'weight': 'bold'}, {'type': 'text', 'text': 'Press', 'size': 'sm', 'align': 'end', 'weight': 'bold', 'color': '#EE4C4C', 'action': {'type': 'message', 'label': 'Click', 'text': 'to to this'}}]}"

解決這個問題的一種方法是拆包

print(type(*mylist))
# <class 'dict'>

如果你想使用字符串操作來做,你可以試試這個,但請記住,以前的方法更好,因為evel 不是一個好習慣

print(type(eval(str(l)[1:-1])))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM