Input Data :
val1 = '[{"EmpID":123456,"AnalystID": "8aa18b9c59XXXXXb20cc2534","173f48XXXXXX427f3f14516dd0"]}]'
Expected Output:
val_op = {"EmpID":123456,"AnalystID": "8aa18b9c59XXXXXb20cc2534","173f48XXXXXX427f3f14516dd0"]}
type(val1)
is str
type(val_op)
is dict
(basically I just need to remove first and last single quote which define Val1
as String).
Approach i tried:
>>> strlen = len(val1)
>>> payloadStr = val1[1:(strlen-1)]
'{"EmpID":123456,"AnalystID":
"8aa18b9c59XXXXXb20cc2534","173f48XXXXXX427f3f14516dd0"]}'
>>> import json
>>>json.loads(payloadsStr)
{'EmpID':123456,'AnalystID':
'8aa18b9c59XXXXXb20cc2534','173f48XXXXXX427f3f14516dd0']}
You don't have to treat the []
separately, json.loads
can handle json list objects.
import json
payload = json.loads(val1)[0]
Also note that the list value in your string is missing an opening bracket and should instead be...
val1 = '[{"EmpID":123456,"AnalystID": ["8aa18b9c59XXXXXb20cc2534","173f48XXXXXX427f3f14516dd0"]}]'
# ^
Since you mentionned the string comes from a web request, this means whoever made that request misformatted their json.
To clarify, this is a string. From the string, you want to extract a dictionary, that is contained in a list.
This makes it more difficult, as opposed to a simple list that contains a dictionary.
One approach you could do is:
val1 = val1.str.split('[')[1].str.split(']')[0]
This should get rid of the brackets, and return an array of 1 index, which contains your dictionary in a string.
Another way, more straightforward is:
val1 = val1.replace('[','').replace(']','')
From there
import json
json.loads(payloadsStr)
Should get you the dictionary.
Thank you all for all the solutions. Since Desired output need to have double quote, hence json.loads(val1) and dict(*eval(val1)) can not be used. I just tried to replace the [] from original string and when passed in Post Request as data payload, it worked fine.
strlen = len(val1)
payloadStr = val1[1:(strlen-1)]
response = requests.request("POST", url, verify=False, data=payloadsStr, headers=header)
response.text
got the output. Apologies for any confusion. Thanks Again
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.