This article mainly introduces you to the relevant information on using Python to determine whether a variable is a string in Json format. The article provides detailed sample code for your reference and study. Friends who need it can take a look below.
Json introduction
Full nameJavaScript Object Notation is a lightweight data exchange format. The most widely used application of Json is as a data format for communication between web servers and clients in AJAX. Nowadays, it is also commonly used in http requests, so it is natural to learn all kinds of json.
This article mainly introduces the use of Python to determine whether a variable is a string in Json format. It has certain reference value for everyone's daily learning work. I won't say much below, let's look at the code directly.
The sample code is as follows
# -*- coding=utf-8 -*- import json def check_json_format(raw_msg): """ 用于判断一个字符串是否符合Json格式 :param self: :return: """ if isinstance(raw_msg, str): # 首先判断变量是否为字符串 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 whether the variable is a string, otherwise if the input is int or this other type, an error will occur.
The output of the above program is:
True False False False
Summary
【Related recommendations】
3. Python object-oriented video tutorial
The above is the detailed content of Python method example for judging Json string. For more information, please follow other related articles on the PHP Chinese website!