0

I have a string in the form of [[sourceId:111, clientId:12345, clientName:testclient, module:test,source:Request, userName:Michelle Jackson],[sourceId:112, clientId:1233, clientName:testclient2, module:test, source:Request, userName:Michelle Jackson]]

How do I convert it into a valid python list of json ?

3
  • 1
    The problem is from where the string is generated. That is not a proper JSON format. If you have control over the source then fix it at source. Commented Nov 28, 2020 at 5:22
  • The problem is I do not have control over source Commented Nov 28, 2020 at 5:23
  • First,you shoud convert your data to dict style,just like: [[{'sourceId':111},{'clientId':12345},{'clientName':'testclient'},{'module':'test'},{'source':'Request'},{'userName':'Michelle Jackson'}], [{'sourceId':112},{'clientId':1233},{'clientName':'testclient2'}, {'module':'test',{'source':'Request'},{'userName':'Michelle Jackson'}]] Your current data format has a syntax error in the list. Commented Nov 28, 2020 at 5:42

1 Answer 1

1

Although I never recommend doing this, here's the code

import re
arr = []
for x in s.split('],['):
    kv = re.sub('\[|\]', '', x)
    arr.append(dict(kvi.split(':') for kvi in kv.split(',')))

NOTE: If the string is system generated, it's better to get it in JSON format in the first place.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.