How to tell that string is a json?
Question: I have a string that I pull from a REST API that is actually a JSON.

I can't use `req.json()` as python doesn't format json correctly i.e. it is
using single quotes and not double quotes, plus it puts a unicode symbol where
there shouldn't be one. This means I can't use it to respond back to REST as
the JSON is not formatted correctly.

However `r.text` prints json that I could use, if I could just tell python:
"this is a json and not a string, take it just as it is and use it as a json".

Is there anyway I could do this? Or is there anyway to tell Python to properly
format json object as per json spec (i.e. not have unicode characters, and use
double quotes).

EDIT:

Apparently this wasn't clear, I apologize.

The issue is that I have to send back a proper JSON formatted object and NOT
python object. Here is what I get:

r.text: {"domain":"example.com", "Link":null, "monitor":"true"}

r.json(): {u'domain':u'example.com', u'Link": None, u'minotor':True}

This is NOT proper JSON formating. You can't have the unicode character, it
isn't None it is null, and it isn't True it is true. You also should have
double and not single quotes (not as big deal I think).

Hope this clarifies my issues.


Answer: You can check if a string is valid json by catching the error.

    
    
    import json
    
    def is_json(myjson):
      try:
        json_object = json.loads(myjson)
      except ValueError, e:
        return False
      return True
    

Test cases:

    
    
    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
    print is_json('{"age":100 }')                #prints True
    print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True
    

