33

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?

3
  • 8
    "… but I don't want to catch exception. I want use if, else…" Paraphrasing: "I don't want to go the easy, obvious way. I want to do it in a way that does not work." No offense intended, just joking! :) Commented Jul 2, 2012 at 13:21
  • no, I had an exception wrapper to all of the application. this should to catch real errors. if I can use if/else, I prefer it.. Commented Jul 2, 2012 at 13:25
  • 9
    I don't get that argument. You can use try/except inside try/except without any problem. Commented Jul 2, 2012 at 13:30

5 Answers 5

68

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 
Sign up to request clarification or add additional context in comments.

5 Comments

TypeError: the JSON object must be str, not 'Response' get this error
fails to validate at single unicode string like u'1589649418441381790', any ideas why?
@lifelogger what version of Python are you using? I ran an interactive python prompt (v2.7.10) with the above code, and when I ran print is_json(u'1589649418441381790') it printed True. If you're using (I believe) v2.6 or earlier, you need the simplejson library
In case of an object of NoneType passed, it throws a TypeError
Imo you should never make it a normality returning from the except block/scope. I would prefer this code if possible. <pre> try: json_object = json.loads(value) return True except JSONDecodeError: pass return False <code>
32

To verify the string would require parsing it - so if you checked then converted it would literally take twice as long. Catching the exception is the best way. Interestingly, you can still use an if-else style expression:

try: json_object = json.loads(json_string) except ValueError as e: pass # invalid json else: pass # valid json 

1 Comment

except ValueError as e for python3
10

Is there any reason you don't want to catch the exception?

Keep in mind that testing and catching an exception can be blazingly fast in Python, and is often the Pythonic way of doing things, instead of testing for type (basically, trust duck typing and react accordingly).

To put your mind a bit more at ease, take a look here: Python if vs try-except

If you're still worried about readability, add a comment to the code to explain why you're using try/except ;)

I struggled with this approach myself in the past coming from a Java background, but this is indeed the simplest way of doing this in Python... and simple is better than complex.

4 Comments

as I said, I had exception wrapper to all of the application. I want this to catch the urgent errors so I can handle them from 1 place. use if else gives my more control on the code and to be sure i didn't except something because anoter reason..
then do the try/except on the minimum block of code possible. You can keep the exception wrapper on your code and use try/except like it's meant to be used all the same.
@eligro: it sounds as if you think you can only catch exceptions in one place, or only for the whole application. This is one place where you want to catch a specific exception because it fits the specific usecase.
+1 for giving reference of performance advantages of try: except.
1

The safest function, which also catches TypeError which happens when None type is passed

import json def json_loads_safe(data): try: return json.loads(data) except (ValueError, TypeError): return None 

Comments

-5

why parsing when you can use types as follows:

def is_json(myjson): return type(myjson) == type({}) def is_json_arr(myjson): return type(myjson) == type([{}]) 

1 Comment

The OP wants to test whether a string contains valid JSON. A string will never satisfy type(myjson) == type({}).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.