Home > Software design >  Convert string to dict without using split in Python Scrapy
Convert string to dict without using split in Python Scrapy

Time:06-11

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

I want data like that without using split:

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

Then access:

JO = json.loads(data)

clientId = JO['clientId']

id = JO['id']

OutPut:

clientId = 300

id = new

CodePudding user response:

My approach is to first add the quotes surrounding the keys to make that string into a valid JSON string, then convert:

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'}

Notes

  • The regular expression (\w ): matches the keys
  • In r'"\1":', the \1 part stands for the matched text in the above.
  • Related