Home > front end >  How to URL encode data in JSON format in Python?
How to URL encode data in JSON format in Python?

Time:07-19

The code:

import urllib.parse

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

The problem: The print function should return {"59764":1} but instead returns 59764=1

Any help is appreciated. Thanks!

CodePudding user response:

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: {"59764": 1}

  • Related