• 21天学Python --- 打卡3: Python && Json


    在这里插入图片描述


                                            活动地址: 21天学习挑战赛.

    在这里插入图片描述


    1.what is json

    JSON(全名:JavaScript Object Notation 对象表示法)是一种轻量级文本数据交换格式。

    • JSON独立于语言
    • JSON具有自我描述性,更易理解
    • JSON比XML更小,更快,更易解析
    • 爬虫经常会获取接口数据,一般都是JSON格式。

    2.json attribute

    {key1:value1, key2:value2…}

    # 格式1JSON 对象
    {"name": "admin", "age": 18}
    
    # 格式2JSON 数组
    {
        "student":
            [
                {"name": "小明", "age": 18},
                {"name": "小红", "age": 16},
                {"name": "小黑", "age": 20}
            ]
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3.json model

    1、使用jsON字符串生成python对象(load)

    2、由python对象格式化成为ison字符串(dump)

    3.1 类型转换

    python transfor json

    PythonJSON
    dictobject
    list, tuplearray
    strstring
    int, float, int- & float-derived Enumsnumber
    Truetrue
    Falsefalse
    Nonenull

    json transforpython

    JSONPython
    objectdict
    arraylist
    stringstr
    number(int)int
    number(real)float
    trueTrue
    falseFalse
    nullNone

    3.2 Json && Python

    方法功能
    json.dumps(obj)将python数据类型转换为json格式的字符串。
    json.dump(obj, fp)将python数据类型转换并保存到son格式的文件内。
    json.loads(s)将json格式的字符串转换为python的类型。
    json.load(fp)从json格式的文件中读取数据并转换为python的类型。

    • json.dumps(obj)
      语法格式:json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
      sort_keys:是否排序
      indent:定义缩进距离
      separators:是一个元组,定义分隔符的类型
      skipkeys:是否允许JSON字串编码字典对象时,字典的key不是字符串类型(默认是不允许)
    >>> import json
    
    # Python字典
    >>> person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
    >>> print(person)
    {'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}
    >>> type(person)
    <class 'dict'
    
    # Python字典转换为json字符串
    >>> jsonStr = json.dumps(person) 
    >>> print(jsonStr )
    {"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true}
    >>> type(jsonStr)
    <class 'str'>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    // 将内容写入json file
    import json
    
    person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
    
    jsonStr = json.dumps(person)
    
    with open('test.json', 'w', encoding='utf-8') as f:  # 打开文件
        f.write(jsonStr)  # 在文件里写入转成的json串
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    • json.dump(obj,fp)
      语法格式:json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
      sort_keys:是否排序
      indent:定义缩进距离
      separators:是一个元组,定义分隔符的类型
      skipkeys:是否允许JSON字串编码字典对象时,字典的key不是字符串类型(默认是不允许)
    import json
    
    person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
    
    json.dump(person, open('data.json', 'w'))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    import json
    
    person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
    
    json.dump(person, open('data.json', 'w'), sort_keys=True, indent=4, separators=(',', ': '))
    
    • 1
    • 2
    • 3
    • 4
    • 5

    • json.loads(s)
      语法格式:json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
    >>> import json
    
    # Python字典
    >>> person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
    >>> print(person)
    {'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}
    >>> type(person)
    <class 'dict'
    
    # Python字典转换为json字符串
    >>> jsonStr = json.dumps(person) 
    >>> print(jsonStr )
    {"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true}
    >>> type(jsonStr)
    <class 'str'>
    
    # json字符串再转换为Python字典
    >>> python_obj = json.loads(jsonStr)
    >>> print(python_obj)
    {'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}
    >>> print(type(python_obj))
    <class 'dict'>
    
    # 打印字典的所有key
    >>> print(python_obj.keys())  
    dict_keys(['name', 'age', 'tel', 'isonly'])
    
     # 打印字典的所有values
    >>> print(python_obj.values()) 
    dict_values(['小明', 30, ['888888', '1351111111'], True])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    import json
    
    f = open('data.json', encoding='utf-8')
    content = f.read()  # 使用loads()方法需要先读文件
    python_obj = json.loads(content)
    print(python_obj)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    • json.load(fp)
      语法格式:json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
    import json
    
    python_obj = json.load(open('data.json','r'))
    print(python_obj)
    print(type(python_obj))
    
    • 1
    • 2
    • 3
    • 4
    • 5

    总结: 不管是dump还是load,带s的都是和字符串相关的,不带s的都是和文件相关的

    3.3 Xml && Json

    pip install xmltodict

    xml transfor json

    import json
    import xmltodict
    
    
    def xml_to_json(xml_str):
        """parse是的xml解析器,参数需要
    
        :param xml_str: xml字符串
        :return: json字符串
        """
        xml_parse = xmltodict.parse(xml_str)
        # json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
        # dumps()方法的ident=1,格式化json
        json_str = json.dumps(xml_parse, indent=1)
        return json_str
    
    
    XML_PATH = './1.xml'  # xml文件的路径
    with open(XML_PATH, 'r') as f:
        xmlfile = f.read()
        with open(XML_PATH[:-3] + 'json', 'w') as newfile:
            newfile.write(xml_to_json(xmlfile))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    在这里插入图片描述
    json transfor xml

    import xmltodict
    import json
    
    
    def json_to_xml(python_dict):
        """xmltodict库的unparse()json转xml
    
        :param python_dict: python的字典对象
        :return: xml字符串
        """
        xml_str = xmltodict.unparse(python_dict)
        return xml_str
    
    
    JSON_PATH = './test.json'  # json文件的路径
    with open(JSON_PATH, 'r') as f:
        jsonfile = f.read()
        python_dict = json.loads(jsonfile)  # 将json字符串转换为python字典对象
        with open(JSON_PATH[:-4] + 'xml', 'w') as newfile:
            newfile.write(json_to_xml(python_dict))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在这里插入图片描述

    4.parse json

    4.1 json string

    import json
    
    json_str = '{"name":"test", "type":{"name":"seq", "parameter":["1", "2"]}}'
    print(json_str)
    print(type(json_str))
    print('-' * 20)
    
    # 1JSON文件转换为Python对象
    python_obj = json.loads(json_str)
    print(python_obj)
    print(type(python_obj))
    print('-' * 20)
    
    # 2、定位具体的数据节点
    print(python_obj.keys())
    print(python_obj.values())
    print(python_obj["name"])
    print(python_obj["type"]["name"])
    print(python_obj["type"]["parameter"][0])
    print(python_obj["type"]["parameter"][1])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    4.1 json file

    {
      "student": {
        "course": {
          "name": "math",
          "score": "90"
        },
        "info": {
          "sex": "male",
          "name": "name"
        },
        "stid": "10213"
      }
    }
    
     
    ```javascript
    import json
    
    # 1JSON文件转换为Python对象
    python_obj = json.load(open('test.json', 'r'))
    print(python_obj)
    print(type(python_obj))
    
    print("-" * 20)
    # 2、解析json文件
    
    # 输出cours节点e下的数据
    print(python_obj['student']['course']['name'])  # 输出name
    print(python_obj['student']['course']['score'])  # 输出score
    
    # 输出info节点下的数据
    print(python_obj['student']['info']['sex'])  # 输出sex
    print(python_obj['student']['info']['name'])  # 输出name
    
    # 输出stid节点下的数据
    print(python_obj['student']['stid'])  # 输出stid
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
  • 相关阅读:
    【Verilog】HDLBits题解——Circuits/Basic Gates
    MFC Windows 程序设计[260]之多种控件展示(附源码)
    PHP如何切割excel大文件,使用 PHP_XLSXWriter 代替 PHPExcel 10W+ 数据秒级导出
    Java进阶学习各种经典书籍电子版
    基于Qt4的磁场单点一致性测试软件开发
    如何用精准测试来搞垮团队?
    把数字字符串倒序
    压力管道的分类
    高度磷酸化的tau蛋白(p-tau)介绍
    平时健身买什么耳机好、分享五款最好的运动耳机推荐
  • 原文地址:https://blog.csdn.net/weixin_43916074/article/details/126157135