I have a string in Python, I want to know if it is valid JSON.
json.loads(mystring)
will raise an error if the string is not JSON but I don't want to catch an exception.
I want something like this, but it doesn't work:
if type(mysrting) == dict: myStrAfterLoading = json.loads(mystring) else: print "invalid json passed"
Do I have to catch that ValueError to see if my string is JSON?
You can try to do json. loads() , which will throw a ValueError if the string you pass can't be decoded as JSON.
To check if a string is JSON in JavaScript, we can use the JSON. parse method within a try-catch block. to check if jsonStr is a valid JSON string. Since we created the JSON string by calling JSON.
@pytest. mark. parametrize("fixture_name", [(path, json)], indirect=True) def test_the_response_status_code_first(fixture_name): assert fixture_name. ok, "The message for the case if the status code !=
The correct answer is: stop NOT wanting to catch the ValueError
.
Example Python script returns a boolean if a string is valid json:
import json def is_json(myjson): try: json_object = json.loads(myjson) except ValueError as e: return False return True print(is_json('{}')) # prints True print(is_json('{asdf}')) # prints False print(is_json('{"age":100}')) # prints True print(is_json('{'age':100 }')) # prints False print(is_json('{"age":100 }')) # prints True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With