在python中将txt转换为json



我有一个关于json和python文本文件的问题。

我有一个。txt文件与cookie,我有大约11个,但我将只显示2。我需要将它们转换为。json文件,以便我可以将它们放在post请求的请求头中。

.txt

中的cookie
Set-Cookie3: X-APPLE-WEBAUTH-PCS-Mail=""TGlzdEFwcGw6MTpBcHBsOjE6AZInfMKt5IWY2iftwASOV2SUGxMMn0ofLN6m6Tl5DsSBDGXPI2Uhfb7IkYx4GWgET2U5FJdBpxnvF1wGPEV2zKGC7UpT2CoDkBSZAGtIHzkmI6zjqXxGS/ObRGVSX4BuUaP6A2Tgt9CKVHzVZG8O+hA8dDxdCy513OkmNYLNRT8a5M7VnDGyqg==""; path="/"; domain=".icloud.com"; path_spec; domain_dot; secure; expires="2022-06-14 13:29:15Z"; HttpOnly=None; version=0
Set-Cookie4: X-APPLE-WEBAUTH-PCS-News=""TGlzdEFwcGw6MTpBcHBsOjE6ARKs9FWrQDcrZGUYbHPO2e7Jux6aRGWLAZt4vjHFRLgqERXDD51hgI8ADM/A3SViCTgpnEfThOKn+rJ4rXRlkyQqq3ZPRdlieQI6g/FYs8RBm5Y0fCcFk5RAHq2VQIibURXAttOjyvVo3JHNuJ38zOmGaytYnSujeI6qFNrtep0YV7Ptq6lKcg==""; path="/"; domain=".icloud.com"; path_spec; domain_dot; secure; expires="2022-06-14 13:29:15Z"; HttpOnly=None; version=0

我想让它们看起来像这样

{
'Set-Cookie3': 'X-APPLE-WEBAUTH-PCS-Mail=""TGlzdEFwcGw6MTpBcHBsOjE6AZInfMKt5IWY2iftwASOV2SUGxMMn0ofLN6m6Tl5DsSBDGXPI2Uhfb7IkYx4GWgET2U5FJdBpxnvF1wGPEV2zKGC7UpT2CoDkBSZAGtIHzkmI6zjqXxGS/ObRGVSX4BuUaP6A2Tgt9CKVHzVZG8O+hA8dDxdCy513OkmNYLNRT8a5M7VnDGyqg==""; path="/"; domain=".icloud.com"; path_spec; domain_dot; secure; expires="2022-06-14 13:29:15Z"; HttpOnly=None; version=0',
'Set-Cookie4': 'X-APPLE-WEBAUTH-PCS-News=""TGlzdEFwcGw6MTpBcHBsOjE6ARKs9FWrQDcrZGUYbHPO2e7Jux6aRGWLAZt4vjHFRLgqERXDD51hgI8ADM/A3SViCTgpnEfThOKn+rJ4rXRlkyQqq3ZPRdlieQI6g/FYs8RBm5Y0fCcFk5RAHq2VQIibURXAttOjyvVo3JHNuJ38zOmGaytYnSujeI6qFNrtep0YV7Ptq6lKcg==""; path="/"; domain=".icloud.com"; path_spec; domain_dot; secure; expires="2022-06-14 13:29:15Z"; HttpOnly=None; version=0'
}

括号不必像那样,它们可以像这样。这个更好,逗号

也很重要
{'cookie': 'value', 'cookie': 'value'}

我尝试了许多解决方案,但其中许多都不起作用,例如认为每个cookie是一个不同的组,所以它们有不同的括号,或者只是引用冒号。任何帮助都会很感激:)谢谢你!

类似的东西应该可以工作:

with open("cookies.txt", "r") as f:  # don't forget to change the filename
txt = f.readlines()
d = {line.split(":", maxsplit=1)[0]: line.split(":", maxsplit=1)[1].lstrip() for line in txt}

输出:

>>> print(d)
{'Set-Cookie3': 'X-APPLE-WEBAUTH-PCS-Mail="\"TGlzdEFwcGw6MTpBcHBsOjE6AZInfMKt5IWY2iftwASOV2SUGxMMn0ofLN6m6Tl5DsSBDGXPI2Uhfb7IkYx4GWgET2U5FJdBpxnvF1wGPEV2zKGC7UpT2CoDkBSZAGtIHzkmI6zjqXxGS/ObRGVSX4BuUaP6A2Tgt9CKVHzVZG8O+hA8dDxdCy513OkmNYLNRT8a5M7VnDGyqg==\""; path="/"; domain=".icloud.com"; path_spec; domain_dot; secure; expires="2022-06-14 13:29:15Z"; HttpOnly=None; version=0n', 'Set-Cookie4': 'X-APPLE-WEBAUTH-PCS-News="\"TGlzdEFwcGw6MTpBcHBsOjE6ARKs9FWrQDcrZGUYbHPO2e7Jux6aRGWLAZt4vjHFRLgqERXDD51hgI8ADM/A3SViCTgpnEfThOKn+rJ4rXRlkyQqq3ZPRdlieQI6g/FYs8RBm5Y0fCcFk5RAHq2VQIibURXAttOjyvVo3JHNuJ38zOmGaytYnSujeI6qFNrtep0YV7Ptq6lKcg==\""; path="/"; domain=".icloud.com"; path_spec; domain_dot; secure; expires="2022-06-14 13:29:15Z"; HttpOnly=None; version=0'}

请注意,正如其他人注意到的那样,dict中不可能有相同的键。

相关内容

  • 没有找到相关文章

最新更新