[英]How do I convert this JSON data into this URL format?
我正在嘗試將這些數據轉換為 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)
時,我得到完全相同的格式。
是否有任何庫或方法可以解決此問題?
您可以使用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 ... '
您正在尋找的是將 json 轉換為查詢字符串。
使用jsonurl
:
import jsonurl
d = {"one" : 1, "two" : 2}
print(jsonurl.query_string(d)) # one=1&two=2
編輯:
不使用任何內置或 3PL:
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])
OUTPUT:
action=submit_user_review&dont-ask-for-email=0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.