Python method example for judging Json string

Y2J
Release: 2017-05-12 10:25:37
Original
2121 people have browsed it

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)
Copy after login

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
Copy after login

Summary

【Related recommendations】

1. Python Free Video Tutorial

2. Python Learning Manual

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!