How do I encode/decode a string properly with .decode("utf-8")?

143 Views Asked by At

I am trying to pass a dict variable to a remote server using BaseHTTPRequestHandler, but using json.dumps(), my server sees:

%7B%22ID%22%3A+%7B%22type%22%3A+%22title%22%2C+%22search%22%3A+%22test%22%7D%7D

instead of:

{id: {'type': 'title', 'search': 'test'}}

I have tried using data.decode("utf-8"), but that is just giving me an error as the data is already a string. I know I'm probably encoding/decoding wrong, but is there any way of getting from what it is already returning into the json format?

1

There are 1 best solutions below

0
On

Take a look at the unquote_plus function from urllib.parse module:

import json
import urllib.parse

text = '%7B%22ID%22%3A+%7B%22type%22%3A+%22title%22%2C+%22search%22%3A+%22test%22%7D%7D'
json_text = urllib.parse.unquote_plus(text)
json_data = json.loads(json_text)
print(json_data)

It outputs

{'ID': {'type': 'title', 'search': 'test'}}