Python数据解析 - json模块处理JSON数据

示例代码

处理Python内置数据类型

# !/usr/bin/env python
# -*- coding:utf-8 -*-

"""
JSON和Python数据类型对应关系(左边JSON,右边Python):
    object      ————————    dict
    array       ————————    list tuple
    string      ————————    str
    int         ————————    int
    true false  ————————    True False
    null        ————————    None

json内置模块处理python内置数据类型:
    dumps(obj)  将Python数据类型转换为JSON格式字符串数据
    dump(obj,file)  将Python数据类型转换为JSON格式字符串数据,并保存到文件中,返回值为None

    loads(jsonStr)  将JSON格式字符串转换为Python数据类型
    load(file)  从文件中读取JSON格式字符串数据,并转换为Python数据类型
"""

import json

# dumps()  loads()
px=0
py=0.1
ps='json'
pls=['a','b',1,'d']
pd={'c':'C','a':'A','b':1}

jx=json.dumps(px)
print(jx,type(jx))
print(json.loads(jx))

jy=json.dumps(py)
print(jy,type(jy))
print(json.loads(jy))

js=json.dumps(ps)
print(js,type(js))
print(json.loads(js))

jarr=json.dumps(pls)
print(jarr,type(jarr))
print(json.loads(jarr))

jobj=json.dumps(pd)
print(jobj,type(jobj))
print(json.loads(jobj))

print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':')))
print(json.dumps({'4': 5, '6': 7},indent=4))

# dump() load()
data={'name':'tom','age':18}
with open('json/data.json',mode='w') as fw:
    json.dump(data,fw)

with open('json/data.json',mode='r') as fr:
    data=json.load(fr)
    print(data,type(data))


处理自定义数据类型

# !/usr/bin/env python
# -*- coding:utf-8 -*-

"""
使用json处理Python class 对象
    dumps(obj,default=function)
    dump(obj,file,default=function)

    loads(jsonStr,object_hook=function)
    load(file,object_hook=function)
"""

import json

class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __str__(self):
        return '姓名:{} 年龄:{}'.format(self.name,self.age)

def person2dict(person):
    """Person类对象到为Json字符串的转换函数"""
    return {
        'name':person.name,
        'age':person.age
    }

def dict2person(d):
    """Json字符串到Person类对象的转换函数"""
    return Person(d['name'],d['age'])

p=Person("张三",18)
data=json.dumps(p,default=person2dict)  # class--->JSON Object
print(data)

p=json.loads(data,object_hook=dict2person)  # JSON Objec--->tclass
print(p)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值