在Python中将具有多个dict的字符串转换为一个字典

oxosxuxt  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(84)

我想把字符串转换成字典,但字符串包含多个字典,所以我该如何转换它请帮助

'{"pr2":[2,"Hair Dryer(Fashion)","₹1499.00","home/images/hairdetyerxyz.png","2"],"pr5":[1,"Bowls(Season bowls )","₹499","home/images/balls_season.png","5"]}{"pr2":[2,"Hair Dryer(Fashion)","₹1499.00","home/images/hairdetyerxyz.png","2"],"pr5":[1,"Bowls(Season bowls )","₹499","home/images/balls_season.png","5"]}'

字符串
请把它转换成一本字典

41ik7eoe

41ik7eoe1#

  • 快速和肮脏 * 的方法是使用str.replace来修复字符串以正确的Json格式。但我建议修复根本原因并更改此字符串的生成方式。
import json

s = '{"pr2":[2,"Hair Dryer(Fashion)","₹1499.00","home/images/hairdetyerxyz.png","2"],"pr5":[1,"Bowls(Season bowls )","₹499","home/images/balls_season.png","5"]}{"pr2":[2,"Hair Dryer(Fashion)","₹1499.00","home/images/hairdetyerxyz.png","2"],"pr5":[1,"Bowls(Season bowls )","₹499","home/images/balls_season.png","5"]}'

data = json.loads("[" + s.replace("}{", "},{") + "]")
print(data)

字符串
印刷品:

[
    {
        "pr2": [
            2,
            "Hair Dryer(Fashion)",
            "₹1499.00",
            "home/images/hairdetyerxyz.png",
            "2",
        ],
        "pr5": [1, "Bowls(Season bowls )", "₹499", "home/images/balls_season.png", "5"],
    },
    {
        "pr2": [
            2,
            "Hair Dryer(Fashion)",
            "₹1499.00",
            "home/images/hairdetyerxyz.png",
            "2",
        ],
        "pr5": [1, "Bowls(Season bowls )", "₹499", "home/images/balls_season.png", "5"],
    },
]

相关问题