python json模块

json是JavaScript对象表示法的缩写,是一种轻量级的数据交换格式,经常被用于Web应用程序中。python中的json库是用于解析和生成json数据格式的库。

import json

data = {
    "name": "张三",
    "age": 18,
    "hobbies": ["reading", "music"],
    "info": {
        "address": "北京市朝阳区",
        "phone": "18888888888"
    }
}

#json.dumps()是用于将python对象序列化为json编码字符串
#ensure_ascii保证每个字符都是ASCII字符
# indent 用于控制缩进的参数
json_str = json.dumps(data, ensure_ascii=False, indent=1)

print(json_str)

# json.loads() 用于将json字符串解码为python对象
data=json.loads(json_str)
print(type(data))
print(data)

import json

# 将json数据写入到文件中
data = {
    "name": "王五",
    "age": 30,
    "hobbies": ["travelling", "photography"],
    "info": {
        "address": "广州市天河区",
        "phone": "13666666666"
    }
}
with open('data.json', 'w') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

# 从文件中读取json数据
with open('data.json', 'r') as f:
    data = json.load(f)
    print(type(data))
    print(data)

 

相关推荐

  1. 驱动模块--内核模块

    2024-01-11 12:48:07       43 阅读
  2. 模块一:登录模块

    2024-01-11 12:48:07       5 阅读
  3. DSP28335模块配置模板系列——EQEP模块配置模板

    2024-01-11 12:48:07       6 阅读
  4. random模块

    2024-01-11 12:48:07       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-11 12:48:07       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-11 12:48:07       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-11 12:48:07       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-11 12:48:07       18 阅读

热门阅读

  1. 【金融支付】常用术语和定义

    2024-01-11 12:48:07       32 阅读
  2. 一、SpringBoot框架搭建

    2024-01-11 12:48:07       34 阅读
  3. C/C++-传值/地址的区别

    2024-01-11 12:48:07       28 阅读
  4. 在IntelliJ IDEA中,.idea文件是什么,可以删除吗

    2024-01-11 12:48:07       33 阅读
  5. Crow:路由局部插件2 调用before_handle

    2024-01-11 12:48:07       40 阅读
  6. C++入门级程序day1

    2024-01-11 12:48:07       36 阅读
  7. Python Selenium常见的报错以及措施

    2024-01-11 12:48:07       34 阅读
  8. Halcon 3D相关算子(二)

    2024-01-11 12:48:07       31 阅读