简体   繁体   中英

Python 3 How to convert data in type list back to dict

How to convert the data in type list back to dict as below sample code. Thanks

[{
                        "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"
                                }
                            }
                        ]
                    }]

so i try to convert back to str and remove "[" , "]" and convert back to dict but the result showing not support format when i bring this to json.dumps as below

"{'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'}}]}"

One way to solve this would be unpacking

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

If you want to do it using string manipulation, you can try this, but keep in mind the previous way is better as evel is not a good practice

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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