浅谈JSON和BSON

JSON (JavaScript Object Notation)JavaScript对象表示法,是一种轻量级的数据交换格式。
JSON 是存储和交换文本信息的语法,类似 XML。比 XML 更小、更快,更易解析。
感觉JSON源于互联网,针对互联网信息的表示、存储,非常方便。并由此产生了BSON,BSON是一种类json的一种二进制形式的存储格式,
简称Binary JSON,它和JSON一样,支持内嵌的文档对象和数组对象,但是BSON有JSON没有的一些数据类型,如Date和BinData类型。
BSON有三个特点:轻量性、可遍历性、高效性。
以上的解释都有些枯燥,更直白地说,用JSON的键值对表示html/JS这些互联网的数据非常方便。比如python中的字典、列表:
 1 import json
 2 data_dict = {
 3     'id': 1,
 4     'name': 'Runoob',
 5     'url': 'http://www.runoob.com'
 6 }
 7 data_list = [1,2,3,4,5]
 8 json_str_dict = json.dumps(data_dict)
 9 json_str_list = json.dumps(data_list)
10 print(type(json_str_dict),json_str_dict,repr(json_str_dict))
11 #>>><class 'str'> 
12 {"id": 1, "name": "Runoob", "url": "http://www.runoob.com"} 
13 '{"id": 1, "name": "Runoob", "url": "http://www.runoob.com"}'
14 print(type(json_str_list),json_str_list,repr(json_str_list))
15 #>>><class 'str'> 
16 [1, 2, 3, 4, 5] 
17 '[1, 2, 3, 4, 5]'
View Code

 

通过以上输出来看,python字典数据、列表数据经过json转换后,变为json的str字符串类型。
而json数据再转回python数据也是很方便的:
 1 python_dict=json.loads(json_str_dict)
 2 python_list=json.loads(json_str_list)
 3 print(type(python_dict),python_dict,repr(python_dict))
 4 #>>><class 'dict'> 
 5 {'id': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'} 
 6 {'id': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'}
 7 print(type(python_list),python_list,repr(python_list))
 8 #>>><class 'list'> 
 9 [1, 2, 3, 4, 5] 
10 [1, 2, 3, 4, 5]
View Code

 

不知道是python成就了json,还是json成就了python。感觉二者之间的联系,不能更密切了吧?比如你可以定义一些json格式的文件,为python程序提供输入或者配置。
而python程序的一些输出结果,也可以用JSON文件存储。python读取、写入JSON文件的程序在这里先不进行,其实也很容易。
再谈BSON,后来的MongoDB数据库专门来存储、管理BSON数据。而BSON又是JSON的二进制格式,那么是否可以认为MongoDB就是从文件管理到数据库管理的一个升级?
或者说,当存在大量的JSON文件的时候,如何管理如何查询如何修改,毕竟这方面是文件的一个劣势,而数据库就应运而生呢?
bson_byte_dict=bson.encode(data_dict)
print(type(bson_byte_dict),bson_byte_dict,repr(bson_byte_dict))
#>>><class 'bytes'>
b'=\x00\x00\x00\x10id\x00\x01\x00\x00\x00\x02name\x00\x07\x00\x00\x00Runoob\x00\x02url\x00\x16\x00\x00\x00http://www.runoob.com\x00\x00'
b'=\x00\x00\x00\x10id\x00\x01\x00\x00\x00\x02name\x00\x07\x00\x00\x00Runoob\x00\x02url\x00\x16\x00\x00\x00http://www.runoob.com\x00\x00'
从上面可以看出,bson通过encode函数处理python的dict数据,变为二进制bytes类型。而且,也很容易再转换回来:
python_dict = bson.decode(bson_byte_dict)
print(type(python_dict), python_dict, repr(python_dict))
#>>><class 'dict'>
{'id': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'}
{'id': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'}
总结上述,JSON、BSON、MongoDB相比于之前的传统关系型数据库,在存储互联网数据方面有很大的优势。而且对于大数据分布式平台来说,Nosql的数据库更方便做分布式处理。当然也
可以不用python语言作为中间的纽带,java一定也可以。


posted @ 2021-05-21 11:28  如知  阅读(1173)  评论(0编辑  收藏  举报