[英]How to convert from List of Dict into Dict?
Input Data :输入数据:
val1 = '[{"EmpID":123456,"AnalystID": "8aa18b9c59XXXXXb20cc2534","173f48XXXXXX427f3f14516dd0"]}]'
Expected Output:预期输出:
val_op = {"EmpID":123456,"AnalystID": "8aa18b9c59XXXXXb20cc2534","173f48XXXXXX427f3f14516dd0"]}
type(val1)
is str
type(val1)
是str
type(val_op)
is dict
type(val_op)
是dict
(basically I just need to remove first and last single quote which define Val1
as String). (基本上我只需要删除将Val1
定义为字符串的第一个和最后一个单引号)。
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.你不必单独对待[]
, json.loads
可以处理 json 列表对象。
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.由于您提到该字符串来自网络请求,这意味着提出该请求的人错误地格式化了他们的 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.这应该去掉括号,并返回一个索引为 1 的数组,其中包含字符串中的字典。
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.由于 Desired output 需要双引号,因此 json.loads(val1) 和 dict(*eval(val1)) 不能使用。 I just tried to replace the [] from original string and when passed in Post Request as data payload, it worked fine.我只是尝试替换原始字符串中的 [],当作为数据有效负载传入 Post Request 时,它工作正常。
strlen = len(val1) strlen = len(val1)
payloadStr = val1[1:(strlen-1)] payloadStr = val1[1:(strlen-1)]
response = requests.request("POST", url, verify=False, data=payloadsStr, headers=header) response = requests.request("POST", url, verify=False, data=payloadsStr, headers=header)
response.text响应文本
got the output.得到了输出。 Apologies for any confusion.对任何混淆表示歉意。 Thanks Again再次感谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.