Created
January 3, 2019 16:00
-
-
Save mtianyan/4cf8c2c55fb01ddf066a00ff8de2188f to your computer and use it in GitHub Desktop.
[python] form_data_to_dict
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import json | |
post_data = """ | |
utf8: ✓ | |
authenticity_token: +3wLsKUPfQGQyMyTuJbJFmdIZZtaoS2QgB9NgSOr0rtoqE1/lmx0WOXpGRh3v+yoXeHeWCtA== | |
session[email_or_mobile_number]: 1147727180@qq.com | |
session[password]: 123456 | |
session[oversea]: false | |
captcha[validation][challenge]: 763dc07fa62749901039eead5a8211cf | |
captcha[validation][gt]: ec47641997d5292180681a247db3c92e | |
captcha[validation][validate]: 230fe13cebd3275c5cc21cc8ce6dffa2 | |
captcha[validation][seccode]: 230fe13cebd3275c5cc21cc8ce6dffa2|jordan | |
session[remember_me]: true | |
""" | |
def post_data_to_dict(post_data_str,isJson=False): | |
line_num = post_data_str.count("\n")-1 | |
re_rule = "(.*):(.*)\n" * line_num | |
re_rules = "\n"+re_rule | |
re_result = re.search(re_rules,post_data_str) | |
key_list = [] | |
value_list = [] | |
if re_result: | |
for x in range(1, line_num*2+1): | |
if x % 2 != 0: | |
key_list.append(re_result.group(x).strip()) | |
elif x % 2 == 0: | |
value_list.append(re_result.group(x).strip()) | |
else: | |
print("Error Deal") | |
return_dict = dict(zip(key_list,value_list)) | |
if isJson: | |
return json.dumps(return_dict,indent=2, sort_keys=True) | |
else: | |
return return_dict | |
print(post_data_to_dict(post_data)) | |
print(post_data_to_dict(post_data,isJson=True)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment