Python determines whether the variable is an example of a string in Json format

  • 2020-06-01 10:04:54
  • OfStack

Json introduction

The full name JavaScript Object Notation is a lightweight data interchange format. Json is most widely used as a data format for communication between web servers and clients in AJAX. It is also now commonly used in http requests, so it is natural to learn about json in various ways.

This article mainly introduces the use of Python to determine whether the variable is Json format string, for everyone's daily learning work has a definite reference value, the following words do not say, directly look at the code.

The sample code is as follows


# -*- coding=utf-8 -*-
import json

def check_json_format(raw_msg):
 """
  Used to determine 1 Whether the string matches Json format 
 :param self:
 :return:
 """
 if isinstance(raw_msg, str):  #  First determine whether the variable is a string 
  try:
   json.loads(raw_msg, encoding='utf-8')
  except ValueError:
   return False
  return True
 else:
  return False

if __name__ == "__main__":
 print check_json_format("""{"a":1}""")
 print check_json_format("""{'a':1}""")
 print check_json_format({'a': 1})
 print check_json_format(100)

First determine if the variable is a string, otherwise an error will occur if you enter int or some other type.

The output of the above program is:


True
False
False
False

conclusion


Related articles: