Issue
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
Solution
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.
Answered By - Hai Vu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.