您的位置:首页 > 编程语言 > Python开发

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

2017-12-21 21:41 573 查看

示例代码

处理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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: