N-line Python code series: two lines of code to convert JSON text into a standard dictionary type

☞ ░LaoYuan Python blog post directory: https://blog.csdn.net/LaoYuanPython/article/details/98245036

I. Introduction

Recently I saw several blog posts similar to "n lines of Python code...". They look pretty good. They are concise and practical. They spread knowledge and brought reading volume. They moved the heart of the old ape and decided to follow suit and push one. " N Lines of Python Code Series " article.

Today we will introduce a simple and fast way to convert JSON text into Python dictionary type using 2 lines of code. For more " n-line Python code series " articles, please refer to the free column " https://blog.csdn.net/laoyuanpython/category_10858655.html n-line Python code series ".

Two, background

When Lao Yuan obtained the comment area information of the CSDN blog post through the program, he found that the returned information was a complex JSON formatted text. The content example is as follows:

{"code":200,"message":"success","data":
     {"count":47,"pageCount":3,"floorCount":27,"list":
         [
             {"info":
                     {"commentId":15302301,"articleId":113663811,"parentId":0,"postTime":"2021-03-07 19:21:17","content":"恭喜你","userName":"ria4com","digg":0,"diggArr":[],"parentUserName":null,"parentNickName":null,"avatar":"https://profile.csdnimg.cn/B/2/3/3_ria4com","nickName":"低代码游戏开发","dateFormat":"1 小时前","tag":"","parentTag":null,"years":null,"vip":null,"vipIcon":null,"companyBlog":null,"companyBlogIcon":null,"flag":null,"flagIcon":null,"levelIcon":null},
              "sub":[],
              "pointCommentId":null
             },
             {
              "info":
                     {"commentId":14922981,"articleId":113663811,"parentId":0,"postTime":"2021-02-05 15:06:21","content":"大佬无敌强","userName":"weixin_44671737","digg":0,"diggArr":[],"parentUserName":null,"parentNickName":null,"avatar":"https://profile.csdnimg.cn/E/3/5/3_weixin_44671737","nickName":"兴趣使然的程序猿","dateFormat":"1 月前","tag":"爱码士","parentTag":null,"years":null,"vip":null,"vipIcon":null,"companyBlog":null,"companyBlogIcon":null,"flag":null,"flagIcon":null,"levelIcon":null},
              "sub":
                     [{"commentId":14923083,"articleId":113663811,"parentId":14922981,"postTime":"2021-02-05 15:13:57","content":"感谢支持!一起加油!","userName":"LaoYuanPython","digg":0,"diggArr":[],"parentUserName":"weixin_44671737","parentNickName":"兴趣使然的程序猿","avatar":"https://profile.csdnimg.cn/0/8/1/3_laoyuanpython","nickName":"LaoYuanPython","dateFormat":"1 月前","tag":"爱码士","parentTag":"爱码士","years":null,"vip":null,"vipIcon":null,"companyBlog":null,"companyBlogIcon":null,"flag":null,"flagIcon":null,"levelIcon":null}],
              "pointCommentId":null
             }
         ]
     }
}

It can be seen that this data is more complicated, but the whole is a text that meets the requirements of the JSON format. Compared with a comment, the managed data is too redundant. Some of the data did not understand the meaning, and only focused on the response code. Code, response message message, number of comments count, comment time postTime, comment content content, comment publisher userName, commenter nickname nickName and other information.

When data analysis is required for the response code, if it is converted into a standard dictionary type, the data access code is easy to implement, so the built-in JSON module of Python is used to convert the above text into a dictionary type, and then the data is analyzed and found to be true It's easy to use.

3. Introduction to Python JSON module

3.1. Overview

The JSON module is a Python built-in module. You don't need to install it separately, you can use it directly by importing it. It is mainly used to serialize and deserialize Python objects. There are four commonly used methods in this module:

  • json.dump

Serialize the Python object into a data stream in Json format and write it to a file type object

  • json.dumps

Serialize a Python object to a string in Json format

  • json.load

Read data in Json format from file type objects and deserialize them into Python objects

  • json.loads

Deserialize a string containing data in Json format into a Python object

3.2 Introduction to loads function

This article mainly uses the loads function of the JSON module to convert character text to the standard built-in Python type.

Call syntax

loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Parameter introduction
  • s: input characters in JSON format, which can be str, bytes, bytearray type
  • *: Named keyword parameter separator. For naming keyword parameters, please refer to the introduction of " https://blog.csdn.net/LaoYuanPython/article/details/94406075 Python中sorted(iterable, *, key=None, reverse=False)函数参数定义中的独立星号(*)的含义 "
  • cls: Specify a custom JsonDecoder subclass to achieve specific deserialization requirements. Generally, there is no need to pay attention to it. The JSONDecoder class is used by default to decode
  • object_hook: An optional parameter, corresponding to a function, used to process the value of the dict type in the Python object generated after decoding, and its return value will replace the dictionary type. This parameter can be used to implement a custom decoder, and generally does not need to be paid separately
  • parse_float: Optional parameter, decodes the string used to process each JSON float type. When not specified, float (num_str) is used by default to decode floating-point number strings
  • parse_int: Optional parameter, will be used to process each JSON int type string decoding. If not specified, int (num_str) is used by default to decode floating-point number strings
  • parse_constant: optional parameter, if specified, it will be called when one of the three strings Infinity, Infinity, and NaN appears
  • object_pairs_hook: optional parameter. If this parameter is specified and set as a callable object, the return value of the object_pairs_hook function replaces the dict type. When this parameter and the object_hook parameter are specified at the same time, object_pairs_hook takes precedence
  • kw: pass some other keyword parameters, when encoding appears in kw, the version after Python 3.1 will ignore the encoding parameter

Fourth, use JSON deserialization to identify JSON text code examples

>>> import json
>>> text = """{"code":200,"message":"success","data":
     {"count":47,"pageCount":3,"floorCount":27,"list":
         [
             {"info":
                     {"commentId":15302301,"articleId":113663811,"parentId":0,"postTime":"2021-03-07 19:21:17","content":"恭喜你","userName":"ria4com","digg":0,"diggArr":[],"parentUserName":null,"parentNickName":null,"avatar":"https://profile.csdnimg.cn/B/2/3/3_ria4com","nickName":"低代码游戏开发","dateFormat":"1 小时前","tag":"","parentTag":null,"years":null,"vip":null,"vipIcon":null,"companyBlog":null,"companyBlogIcon":null,"flag":null,"flagIcon":null,"levelIcon":null},
              "sub":[],
              "pointCommentId":null
             },
             {
              "info":
                     {"commentId":14922981,"articleId":113663811,"parentId":0,"postTime":"2021-02-05 15:06:21","content":"大佬无敌强","userName":"weixin_44671737","digg":0,"diggArr":[],"parentUserName":null,"parentNickName":null,"avatar":"https://profile.csdnimg.cn/E/3/5/3_weixin_44671737","nickName":"兴趣使然的程序猿","dateFormat":"1 月前","tag":"爱码士","parentTag":null,"years":null,"vip":null,"vipIcon":null,"companyBlog":null,"companyBlogIcon":null,"flag":null,"flagIcon":null,"levelIcon":null},
              "sub":
                     [{"commentId":14923083,"articleId":113663811,"parentId":14922981,"postTime":"2021-02-05 15:13:57","content":"感谢支持!一起加油!","userName":"LaoYuanPython","digg":0,"diggArr":[],"parentUserName":"weixin_44671737","parentNickName":"兴趣使然的程序猿","avatar":"https://profile.csdnimg.cn/0/8/1/3_laoyuanpython","nickName":"LaoYuanPython","dateFormat":"1 月前","tag":"爱码士","parentTag":"爱码士","years":null,"vip":null,"vipIcon":null,"companyBlog":null,"companyBlogIcon":null,"flag":null,"flagIcon":null,"levelIcon":null}],
              "pointCommentId":null
             }
         ]
     }
}"""
>>> response = json.loads(text)
>>> print(response['code'],response['data']['count'],response['data']['list'][0]['info']['nickName'],response['data']['list'][0]['info']['content'])
200 47 低代码游戏开发 恭喜你
>>> 

As you can see, in the above case, only the import function loads is needed to convert the JSON text into a Python dictionary object, and then loads can be used to perform deserialization. The conversion of JSON text to dictionary type is completed with 2 lines of code.

V. Summary

This article introduces the method and case of using the Python built-in module JSON to convert JSON format text into Python standard dictionary type. The JSON text can be processed simply and quickly through the loads of the JSON module, and standard Python objects can be generated to facilitate subsequent program access.

Blogging is not easy, please support:

If you have gained something from reading this article, please like, comment, and bookmark. Thank you for your support!

If you have any questions about the content of the article, you can leave a message in the blog comment area, or follow: Lao Yuan Python WeChat public account to send a message for consultation.

For more introduction to Python crawler introduction , please refer to the column "Python crawler introduction"

Column URL : https://blog.csdn.net/laoyuanpython/category_10762553.html

Paid column about the old ape

  1. The paid column " https://blog.csdn.net/laoyuanpython/category_9607725.html Using PyQt to Develop Graphical Interface Python Applications" specifically introduces the basic tutorials of Python-based PyQt graphical interface development. The corresponding article directory is " https://blog.csdn .net/LaoYuanPython/article/details/107580932 Use PyQt to develop a graphical interface Python application column directory ";
  2. The paid column " https://blog.csdn.net/laoyuanpython/category_10232926.html moviepy audio and video development column ) details the related methods of moviepy audio and video editing and synthesis processing and the use of related methods to process related editing and synthesis scenes, corresponding to the article The directory is " https://blog.csdn.net/LaoYuanPython/article/details/107574583 moviepy audio and video development column article directory ";
  3. The paid column " https://blog.csdn.net/laoyuanpython/category_10581071.html OpenCV-Python Difficult Questions for Beginners " is " https://blog.csdn.net/laoyuanpython/category_9979286.html OpenCV-Python graphics and image processing "The companion column" is an integration of the author’s personal perceptions of some of the problems encountered in the learning of OpenCV-Python graphics and image processing. The relevant information is basically the result of repeated research by the old ape, which helps OpenCV-Python beginners to more in-depth To understand OpenCV, the corresponding article directory is " https://blog.csdn.net/LaoYuanPython/article/details/109713407 OpenCV-Python Beginners Difficult Question Collection Column Directory "
  4. The paid column " https://blog.csdn.net/laoyuanpython/category_10762553.html Introduction to Python Crawlers" introduces the content of crawler development from the perspective of an Internet front-end developer, including the basic knowledge of crawler introduction and crawling Take CSDN article information, blogger information, like articles, comments and other actual content.

The first two columns are suitable for novice readers who have a certain Python foundation but no relevant knowledge. The third column, please combine " https://blog.csdn.net/laoyuanpython/category_9979286.html OpenCV-Python graphics and image processing " Learning to use.

For those who lack Python foundation, you can learn Python from scratch through Lao Yuan’s free column " https://blog.csdn.net/laoyuanpython/category_9831699.html column: Python basic tutorial directory ).

If you are interested and willing to support the readers of Old Ape, welcome to buy paid columns.

Learn Python from the old ape!

☞ ░Go to LaoYuanPython blog post directory https://blog.csdn.net/LaoYuanPython

Guess you like

Origin blog.csdn.net/LaoYuanPython/article/details/114493459