Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify if a String is JSON in python?

Tags:

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?

like image 238
eligro Avatar asked Jul 02 '12 13:07

eligro


People also ask

How check data is JSON or not in Python?

You can try to do json. loads() , which will throw a ValueError if the string you pass can't be decoded as JSON.

How do I know if a text is 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.

How do you assert a JSON response in Python?

@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 !=


1 Answers

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 
like image 142
JosefAssad Avatar answered Oct 15 '22 21:10

JosefAssad