我如何将JSON数据转换为URL格式?

问题描述 投票:0回答:2

我正在尝试将这些数据转换为URL格式(我不知道其技术术语,但我想您知道我在问什么)这个Body数据:


body = {
        'dont-ask-for-email': 0,
        'action': 'submit_user_review',
        'post_id': 61341,
        'email': '',
        'subscribe': 1,
        'previous_hosting_id': '',
        'fb_token': '',
        'title': 'I suggest you guys to add more services',
        'summary': 'So far, so good. Quick response, better prices and effective support. All a com>
        'score_reliability': 10,
        'score_pricing': 10,
        'score_userfriendly': 10,
        'score_support': 10,
        'score_features': 10,
        'hosting_type': 'dedicated-server',
        'author': 'Andrew McCarthy',
        'social_link': '',
        'site': '',
        'screenshot[image][]': '',
        'screenshot[description][]': '',
        'user_data_process_agreement': 1,
        'user_email_popup': '',
        'subscribe_popup': 1,
        'email_asked': 0
}

我需要这种格式来运行我的python脚本

jsondata = 'dont-ask-for-email=0&action=submit_user_review&post_id=61341&email=&subscribe=1&previous_hosting_id=&fb_token=&title=I+suggest+you+guys+to+add+more+services&summary=So+far,+so+good.+Quick+response,+better+prices+and+effective+support.+All+a+company+needs,+they+got+it.&score_reliability=10&score_pricing=10&score_userfriendly=10&score_support=10&score_features=10&hosting_type=dedicated-server&author=Manik+Lal&social_link=&site=&screenshot%5Bimage%5D%5B%5D=&screenshot%5Bdescription%5D%5B%5D=&user_data_process_agreement=1&user_email_popup=&subscribe_popup=1&email_asked=1'

我尝试与之倾倒

jsondata = json.dumps(body)

运行代码后,当我print(jsondata)时,我得到完全相同的格式。

是否有任何库或方法可以解决此问题?

python json urllib
2个回答
2
投票

您可以使用urllib.parse.urlencode方法将字典编码为url参数字符串:

import urllib.parse
encoded = urllib.parse.urlencode(body)
# encoded = 'dont-ask-for-email=0&action=submit_user_review&post_id=6134 ... '

0
投票

您正在寻找的是将json转换为querystring。

使用jsonurl

jsonurl

编辑

不使用任何内置或3PL:

import jsonurl    
d = {"one" : 1, "two" : 2}    
print(jsonurl.query_string(d))   # one=1&two=2

输出:

body = {
        'dont-ask-for-email': 0,
        'action': 'submit_user_review',
        }            

query_str = ''
for key in body.keys():
    query_str += str(key) + '=' + str(body[key]) + "&"

print(query_str[:-1])
© www.soinside.com 2019 - 2024. All rights reserved.