• Python快速上手JSON指南


    什么是JSON?

    网上对JSON有很多教程,有各种各样的解释。一言以蔽之,JSON本质上是一种语法,这种语法的作用是把数据以字符串的形式存储、传递,多用于Web编程。

    JSON的典型示例

    '{
    "employees": [
    { "firstName":"Bill" , "lastName":"Gates" },
    { "firstName":"George" , "lastName":"Bush" },
    { "firstName":"Thomas" , "lastName":"Carter" }
    ]
    }'

    从Python的角度理解JSON,JSON的主要构成要素只有两个:字典,字符串。大家可以把JSON理解为字符串化的字典。

    以上面的典型示例为例子,"employees"为key, 后面的由3个字典组成的列表就为Value. 这就构成了一份JSON数据.

    利用Packge json解析、生成JSON

    利用json的loads和dumps两个函数,基本可以满足需求。我们假设上述JSON典型示例字符串为Json_str,话不多说,直接上代码:

    >>> import json
    >>> Json_afterdecode = json.loads(Json_str)
    >>> print(type(Json_afterdecode))
    <class 'dict'>
    >>> Json_afterdecode
    {'employees': [{'lastName': 'Gates', 'firstName': 'Bill'}, {'lastName': 'Bush', 'firstName': 'George'}, {'lastName': 'Carter', 'firstName': 'Thomas'}]}
    >>> Json_afterdecode["employees"][0]["lastName"]
    'Gates'
    >>> Json_afterencode = json.dumps(Json_afterdecode)
    >>> print(type(Json_afterencode))
    <class 'str'>
    >>> Json_afterencode
    '{"employees": [{"lastName": "Gates", "firstName": "Bill"}, {"lastName": "Bush", "firstName": "George"}, {"lastName": "Carter", "firstName": "Thomas"}]}'

    优雅的输出

    很多时候我们需要把JSON放到文件里,变成JSON文件(比如需要用JSON文件存储一些配置信息时),但是一行字符串丑的不行,怎么办?

    json.dumps(<你要转换为JSON的data>, sort_keys=True, indent=4)),可以实现排序和缩进

    >>> Json_afterencode_elegant = json.dumps(Json_afterdecode, sort_keys=True, indent=4)
    >>> print(Json_afterencode_elegant)
    {
        "employees": [
            {
                "firstName": "Bill",
                "lastName": "Gates"
            },
            {
                "firstName": "George",
                "lastName": "Bush"
            },
            {
                "firstName": "Thomas",
                "lastName": "Carter"
            }
        ]
    }

    瞧,这样不仅看起来美观,也便于其他人往Json里填充数据。

    当我们需要从JSON文件里读取信息时,直接用下面的路径就能直接得到JSON数据了。

    >>> Json_afterdecode = json.loads(open("JSON文件路径","r").read())

    参考链接:

        RUNOOB的JSON教程: http://www.runoob.com/json/json-tutorial.html

  • 相关阅读:
    switch的使用
    ArrayAdapter的使用
    android的xml中怎么实现按钮按下去变颜色
    Intent跳转的设置和Bundle的使用
    监听JList列表项的单击事件
    草稿
    Android背景图覆盖状态栏(我的手机安卓版本是4.2.2)
    RSA加密解密 (输入数值)
    仿射密码加密解密 (输入字母数值)
    Intent.ACTION_PICK
  • 原文地址:https://www.cnblogs.com/ArsenalfanInECNU/p/6249454.html
Copyright © 2020-2023  润新知