首页 > 编程语言 >python-标准库json模块的使用

python-标准库json模块的使用

时间:2023-01-13 10:11:32浏览次数:46  
标签:obj python json computer 模块 print import type

python-标准库json模块

1. 标准库json模块

  • JSON是一种轻量级数据交换格式,一般API返回的数据大多是JSON、XML,如果返回JSON的话,需将获取的数据转换成字典,方面在程序中处理。

  • json与pickle有相似的接口,主要提供两种方法:

    • dumps() 对数据进行编码
    • loads() 对数据进行解码
  • 示例

    • 将字典类型转换为json对象

      import json
      computer = {"主机":5000,"显示器":1000,"鼠标":60,"键盘":150}
      json_obj = json.dumps(computer)
      print(type(json_obj))
      print(json_obj)
      
    • 将json对象转换为字典

      import json
      data = json.loads(json_obj)
      print(type(data))
      

2. 案例

#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py

import json
computer  = {
    "name":"汪峰",
    "age": 18,
    "hobby":"上头条",
    "wife":{
        "name":"子怡",
        "age":19,
        "hobby":["唱歌","跳舞","演戏"]
    }
}

json_obj = json.dumps(computer,ensure_ascii=False)  # json处理中文要加ensure_ascii=False,禁止使用ascii码转化中文
print(type(json_obj))
print(json_obj)


import json
data = json.loads(json_obj)
print(type(data))
print(json_obj)

标签:obj,python,json,computer,模块,print,import,type
From: https://www.cnblogs.com/scajy/p/17048707.html

相关文章