How do I validate an x-www-form-urlencoded string without using its contents or header

Viewed 35

I understand that I can validate json as such:

import json

jsondump = json.dumps(jsonstring)

if json.loads(jsondump):
    print("Valid")
else:
    ("no")

I am trying to distinguish between a JSON string and an x-www-form-urlencoded string. I would like to do this without using the content of the string or check if keys are present to identify this.

I know that the MIME type of a file can be used to identify the content type however, I am not using file as input but rather a string from a variable.

My question is: Can I identify if the content type is x-www-form-urlencoded without using the contents of the string or using a content-type header?

1 Answers

Without checking the Content-Type header in the response, it could be hard to validate that the response data is a JSON string rather than a x-www-form-urlencoded string.

Note that there is nothing wrong with how you were validating the data; using json.loads to confirm that the JSON string is valid seems a good idea as any to me.

However, if you are sure that a server only responds back with either a valid JSON string or x-www-form-urlencoded data, then you probably could simplify this check a little in the interests of time (and performance, to some degree) as shown below.

Essentially here, instead of loading the whole JSON string into memory via json.loads, we only check the start character which marks the beginning of a valid JSON string.

response_string = '  [{"test": "value"}] '

trimmed = response_string.lstrip()
is_json_string = trimmed.startswith(('[', '{'))

print(is_json_string)  # True
Related