Search code examples
pythonjsonencodeurlencode

How to URL encode data in JSON format in Python?


The code:

import urllib.parse

print(urllib.parse.urlencode({"59764":1}))

The problem: The print function should return %7B%2259764%22%3A1%7D but instead returns 59764=1

Any help is appreciated. Thanks!


Solution

  • You're urlencoding a dictionary.

    Instead, you should json.dumps the dictionary to a string then quote it:

    import json
    import urllib.parse
    
    value_dict = {"59764": 1}
    value_str = json.dumps(value_dict)
    print(urllib.parse.quote(value_str))
    

    Output: %7B%2259764%22%3A%201%7D