关于java:Python-Json使用

6次阅读

共计 2482 个字符,预计需要花费 7 分钟才能阅读完成。

Python Json 应用

本篇次要介绍一下 python 中 json 的应用 如何把 dict 转成 json、object 转成 json、以及 json 转成对象 等等。。

json 是十分罕用的一种数据格式,比方在前后端拆散的 web 开发中,返回给前端 通常都会应用 json,那么来看看 python 中如何玩转 json

1.dict 转成 json (json.dumps(dict))

留神:ensure_ascii=False 否则中文乱码

import json

 student = {
     'name': 'johnny',
     'age': 27,
     'address': '无锡'
 }

 print(json.dumps(student, ensure_ascii=False))
# {"name": "johnny", "age": 27, "address": "无锡"}  json

2.json 转 dict(json.loads(jsonstr))

import json

json_student = '{"name":"johnny","age": 27,"address":" 无锡 "}'

print(json.loads(json_student))
# {'name': 'johnny', 'age': 27, 'address': '无锡'} 字典 dict

3. 类对象转 json (dict 属性 / 提供 default= 办法)

3.1 谬误应用

留神:json.dumps() 不反对 间接把 类对象放进去!!!会报错 Student is not JSON serializable

import json


class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
student = Student('candy', '30')
#谬误应用!!!print(json.dumps(student))  报错!!!TypeError: Object of type Student is not JSON serializable
3.2 应用类对象 dict 属性
# 正确应用!!!print(json.dumps(student.__dict__))) #能够应用 类对象的 __dict__ 属性
#{"name": "candy", "age": "30"}
3.3 提供一个 convert2json 办法

default= 指定办法

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    @staticmethod
    def conver2json(self):
        return {
            'name': self.name,
            'age': self.age
        }
#通过本人写一个 conver2json 办法 去手动转化一下 把 类对象转成 json 
print(json.dumps(student,default=Student.conver2json))

4.json 转 类对象(json.loads(jsonstr,object_hook=..))

留神:json.loads 默认只会转成 dict, 须要本人提供办法 把 dict 转成 类对象

import json

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    @staticmethod
    def conver2json(self):
        return {
            'name': self.name,
            'age': self.age
        }
        
    @staticmethod
    def convert2object(dict):
        return Student(dict['name'],dict['age'])

json_student = '{"name":"johnny","age": 27,"address":" 无锡 "}'
print(json.loads(json_student,object_hook=Student.convert2object))
#<__main__.Student

5. dict/ 对象 转为 json 文件(json.dump(student,f))

留神 dump 还是 只能接管 dict,如果要把 对象写到 json 中 须要先把对象 转成 dict,能够通过 ——dict——属性

student = {
    'name': 'johnny',
    'age': 27,
    'address': '无锡'
}
with open('student.json','w') as f:
    json.dump(student,f,ensure_ascii=False)

6. json 文件转 dict / 对象 (json.load)

with open('student.json','r')  as f:
    print(json.load(f))

小疑难

为什么:转成 json 后 name 是一个数组呢?因为 self.name = name, 前面有一个 逗号,。。。会把这个 name 当成元组,元组转成 json 就是 数组!!!

class Student:
    def __init__(self, name, age):
        self.name = name,  #这里!!!不能有 逗号。。self.age = age


student = Student('candy', '30')
print(json.dumps(student.__dict__))
#猜猜它的打印是什么 

#{"name": ["candy"], "age": "30"}   

总结

  1. json.dumps() 只反对 dict 转 json 如果是 class 对象 须要 通过 dict 属性或者提供 default= conver2json 办法
  2. json.dump() 是写入 文件中
  3. json.loads() 只反对把 json str 转成 dict,如果要转成 class 对象 则须要提供 object_hook=convert2object 办法
  4. json.load()/ 是从文件中读取 jsonstr 到 dict

很简略 留神一下 class 和 json 的互相转化即可

参考:http://www.kaotop.com/it/2650…

欢送大家拜访 集体博客 Johnny 小屋
欢送关注集体公众号

正文完
 0