Introduction to json files and parsing json files with the help of python


Author:qyan.li

Date:2022.6.13

Topic: Analysis of Jsonfile usage and file Pythonmanipulation with the help of languageJson

One, written in front:

         ~~~~~~~~         Some time ago, I flipped through python programming and practice, and found that there is a chapter about the analysis of Json files and the construction of maps. I have heard about Json files many times, and occasionally come into contact with them, but I still don’t know exactly what Json files are, what they are used for, and how to use them. So simply learn and sort out the content of the Json file, and write a blog post to record it.

Two, Json file introduction and python analysis

         ~~~~~~~~         I don't have a deep understanding of the detailed official definition of the Json file. According to my personal understanding, Json文件是能够保留原始数据类型的文件(personal understanding). A simple chestnut may be clearer and clearer. For example, use the python language to save a program-generated list list = [1,2,3,4,5,6,7,8,9] into a txt file, When you read the txt file, the format of the read data content may be the same, but use type to check the data type and find that the read is a string, which means that this object can no longer be used at this time The related methods of the list can be used to operate, losing the original characteristics, and can only be operated by the method of the string. But to some extent, the json file can make up for this: write a dictionary into the json file, and the original data type can be retained when the list is taken out, which is convenient for subsequent operations in the program.

         ~~~~~~~~         The concepts of serialization and deserialization may be involved here: serialization refers to converting objects into byte sequences, and deserialization refers to restoring and reconstructing byte sequences into objects. The purpose of serialization and deserialization is the preservation and reconstruction of object state. Serialization and deserialization make it possible to guarantee the integrity and transferability of objects when passing and saving objects. Convert an object to an ordered byte stream for transmission over the network or storage in a local file.


         ~~~~~~~~         With the help of the python language to operate the json file, mainly with the help of the json module, the writing and reading of the json file can be completed. The following will combine the specific code to briefly explain the use of the json module in python:

  • Write python object into json file

             ~~~~~~~~         Write python objects into json files, mainly by means of the dumps and dump functions of the json module, dumps() converts python objects into json objects, and dump() writes python objects into json files in the form of json objects

    def writeIntoJsonFile():
        ## 创建python对象
        TestDict = {
          
          
            'name':'liqiyan',
            'age':10,
            'address':'chengdu',
            'friends':['dale','blender','mark']
        }
        TestLst = ['a','b','c','d']
        IntoData = [TestDict,TestLst]
    	## 将python对象转化为json对象
        JsonData1 = json.dumps(TestDict)
        JsonData2 = json.dumps(TestLst)
        # print(type(JsonData2)) # json对象的格式为字符串str
    
    	## 将python对象写入json文件
        with open('./Test.json','w') as f:
            # json.dump(JsonData,f)
            json.dump(IntoData,f)
    

    Note Tips for writing python objects to json files:

    Note that the first parameter of the dump(data,file) function is a python object, not the object after dumps, and the python object passed in the above code should be a python object of type TestDict, TestLst, and IntoData, not a json of type JsonData1 or JsonData2 object, if a json object is passed in, there will be many slashes in the content of the json file

  • Read json file as python object

             ~~~~~~~~        To read the contents of the json file, mainly rely on the load and loads functions of the json module. The load function reads the contents of the json file to form a python object, and the loads function converts the json type string into a python object.

    def ReadJsonFile(FilePath):
        ## load函数读取json文件
        with open(FilePath,'r') as f:
            object = json.load(f)
            print(object) # type->dict
        
        ## loads函数还原python对象
        TestDict = {
          
          'name':'qyan.li','age':10}
        JsonDict = json.dumps(TestDict) # type->str
        PythonDict = json.loads(JsonDict) # type->dict
    

         ~~~~~~~~        The above code shows the general method of reading the json file with the help of the load function. The read object is the converted python object. When there is more than one data in the json file, the read is stored in the form of i in the list. The function of the loads function is to convert the json object (corresponding to dumps) into a python object.

3. Summary

         ~~~~~~~~         Json files provide us with convenience in some cases, especially when saving files involving variables generated by programs, it is not necessary to use txt files in the future. In some cases, Json files may be a better choice.

Guess you like

Origin blog.csdn.net/DALEONE/article/details/125338747