在Python Scrapy中不使用分割将字符串转换为字典

cld4siwp  于 2022-11-09  发布在  Python
关注(0)|答案(1)|浏览(142)
data = '{clientId: "300",id: "new",ctime: "6/3/2022",mtime: "6/3/2022"}'

我希望在不使用分割的情况下获得这样的数据:

data = {"clientId": "300","id": "new","ctime": "6/3/2022","mtime": "6/3/2022"}

然后访问:

JO = json.loads(data)

clientId = JO['clientId']

id = JO['id']

输出:

clientId = 300

id = new
h22fl7wq

h22fl7wq1#

我的方法是首先在键周围添加引号,使该字符串成为有效的JSON字符串,然后进行转换:

import json
import re

data = '{clientId: "300",id: "new",ctime: "6/3/2022",mtime: "6/3/2022"}'

valid = re.sub(r"(\w+):", r'"\1":', data)

# '{"clientId": "300","id": "new","ctime": "6/3/2022","mtime": "6/3/2022"}'

json_object = json.loads(valid)

# {'clientId': '300', 'id': 'new', 'ctime': '6/3/2022', 'mtime': '6/3/2022'}

注解

  • 正则表达式(\w+):与键匹配
  • r'"\1":'中,\1部分代表上面的匹配文本。

相关问题