python学习之——python数据 和 json数据的转化

json的应用:

1、json数据常常是http网络传输格式,所以常常用到python数据和json数据的格式转化

2、实现不同的编程语言之间对象的传递,把对象序列化为标准格式

不同的编程语言有不同的数据类型; 比如说:
Python的数据类型有(dict、list、string、int、float、long、bool、None)
Java的数据类型有(bool、char、byte、short、int、long、float、double)
C的数据类型有(bit、bool、char、int、short、long、unsigned、double、float)
Tcl的数据类型(int、bool、float、string)
Ruby的数据类型(Number、String、Ranges、Symbols、true、false、Array、Hash)
...
他们的共同特点是,都有字符串类型!
所以要实现不同的编程语言之间对象的传递,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。
JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便.

 

Python内置的json模块提供了非常完善的Python对象到JSON格式的转换。

json.dumps()         将Python中的对象转换为JSON中的字符串对象
json.loads()         将JSON中的字符串对象转换为Python中的对象

1、简单的python对象转化为json数据

import json
# json.dumps():接收python类型的数据作为参数,返回了一个str对象的encodedjson(从python数据转换为json);
# json.loads():接收json字符串,返回python类型的数据(从json字符串转换为python数据)

a = {"name":"li_ming", "age":20}
b = "I love China"
c = [[1,2],[3,4],[5,6]]

# python 转 json
a_json = json.dumps(a)
b_json = json.dumps(b)
c_json = json.dumps(c)
print(type(a_json))
print(type(b_json))
print(type(c_json))

# json 转 python
a_new = json.loads(a_json)
b_new = json.loads(b_json)
c_new = json.loads(c_json)

print(type(a_new))
print(type(b_new))
print(type(c_new))


# 输出
<class 'str'>
<class 'str'>
<class 'str'>
<class 'dict'>
<class 'str'>
<class 'list'>

2、python读写json文件

json.dump()         将Python对象转成字符串存到json文件
json.load()           从json文件读取内容转换为Python对象

import json

# python对象写入json文件
o_dict = {"name":"li_ming", "age":20}
with open("test.json", "w") as f_w:
    json.dump(o_dict, f_w)


# json文件读出到python对象
with open("test.json", "r") as f_r:
    r_dict = json.load(f_r)
    print(r_dict)

3、python自定义类对象转化为json

首先看一下类的__dict__属性和类对象的__dict__属性:

# -*- coding: utf-8 -*-

class A(object):

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def test(self):
        print 'a normal func.'

    @staticmethod
    def static_test(self):
        print 'a static func.'

    @classmethod
    def class_test(self):
        print 'a calss func.'


obj = A(2, 3)
print A.__dict__
print("***************************")
print obj.__dict__

运行结果:

{'a': 0, '__module__': '__main__', 'b': 1, 'class_test': <classmethod object at 0x00000000021882E8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__init__': <function __init__ at 0x00000000023A5BA8>, 'test': <function test at 0x00000000023A5C18>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': '\n    Class A.\n    ', 'static_test': <staticmethod object at 0x00000000021881C8>}
*********************************
{'a': 2, 'b': 3}

由此可见, 类的静态函数、类函数、普通函数、全局变量以及一些内置的属性都是放在类__dict__里的

对象的__dict__中存储了一些self.xxx的一些东西

import json

class Myclass():

    def __init__(self, name, age):

        self._name = name
        self._age = age

c = Myclass("li_ming", 20)

c_dict = c.__dict__

result_json = json.dumps(c_dict)

print(result_json)
print(type(result_json))


result_python = json.loads(result_json)
print(result_python)
print(type(result_python))


# 输出
{"_name": "li_ming", "_age": 20}
<class 'str'>
{'_age': 20, '_name': 'li_ming'}
<class 'dict'>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值