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

Python对Json的操作

2016-09-25 16:55 274 查看
“Json是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,‘名称/值’对的集合数据结构”

python中对简单数据类型的编码(encoding)和解析(decoding)

mport json

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

if __name__=='__main__':
obj=[[1,2,3],123,123.123,'abc',{'key1':(1,2,3),'key2':(4,5,6)}]
#对数据进行encode
encodejson=json.dumps(obj,'asdf')
print(repr(obj))
print(encodejson)

#对数据进行decode
#json.loads()
decodejson=json.loads(encodejson)
print(decodejson)
#输出:
# [[1, 2, 3], 123, 123.123, 'abc', {'key1': (1, 2, 3), 'key2': (4, 5, 6)}]
# [[1, 2, 3], 123, 123.123, "abc", {"key1": [1, 2, 3], "key2": [4, 5, 6]}]
# [[1, 2, 3], 123, 123.123, 'abc', {'key1': [1, 2, 3], 'key2': [4, 5, 6]}]


注意到数据编码解析前后数据的变化

更详细的一些基本操作:http://docs.python.org/library/json.html



Json数据变化过程对照表(来至库源码)

+---------------+-------------------+
| JSON | Python |
+===============+===================+
| object | dict |
+---------------+-------------------+
| array | list |
+---------------+-------------------+
| string | str |
+---------------+-------------------+
| number (int) | int |
+---------------+-------------------+
| number (real) | float |
+---------------+-------------------+
| true | True |
+---------------+-------------------+
| false | False |
+---------------+-------------------+
| null | None |
+---------------+-------------------+

+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str | string |
+-------------------+---------------+
| int, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+

这是简单的数据处理,当然我们也可以处理自己定义的数据。如学生、老师等对象
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: