美文网首页
python当中json相关知识

python当中json相关知识

作者: 慕慕她爸 | 来源:发表于2019-08-17 11:03 被阅读0次

    json基本概念

    • 一种轻量级的数据交换格式;通用,跨平台
    • "键值对" 的集合;值的有序集合
    • 类似于python中的字典dict

    python-json数据类型对应关系

    python数据类型 json数据类型
    dict object
    list,tuple array
    str str
    int,float num
    True true
    False false
    None null

    常见操作

    1. python数据转换为json对象
    2. json字符串转换为python对象
    3. 从文件中读取json字符串,转换为python对象
    #coding:utf-8
    
    import json
    
    def python_to_json():
        """
        将python对象转换为json
        :return:
        """
        d = {
            'name':  'python书籍',
            'price': 777,
            'is_valid': True
        }
        rest = json.dumps(d, indent=4)
        print(rest)
    
    def json_to_python():
        """
        将json字符串转换为python字符串
        :return:
        """
        data = '''
            {
                "name": "Python书籍",
                "origin_price": 66,
                "pub_date": "2018-4-14 17:00:00",
                "store": ["京东", "淘宝"],
                "author": ["张三", "李四", "Jhone"],
                "is_valid": true,
                "is_sale": false,
                "meta": {
                    "isbn": "abc-123",
                    "pages": 300
                },
                "desc": null
        }
        '''
        rest = json.loads(data)
        print(rest)
        print(rest['name'])
    
    def json_to_python_from_file():
        """
        从文件读取内容,并转换成python对象
        :return: 
        """
        with open('book.json', 'r', encoding='utf-8') as f:
            s = f.read()
            print(s)
            rest = json.loads(s)
            print(rest)
            print(rest['name'])
        f.close()
    
    
    if __name__ == '__main__':
        python_to_json()
        json_to_python()
        json_to_python_from_file()
    

    注意事项

    • json串中必须是双引号
    • json键值必须唯一

    相关文章

      网友评论

          本文标题:python当中json相关知识

          本文链接:https://www.haomeiwen.com/subject/deyhsctx.html