您当前的位置:首页 > 互联网教程

LowDB 轻量级 JSON 本地数据库

发布时间:2025-05-20 02:51:49    发布人:远客网络

LowDB 轻量级 JSON 本地数据库

一、LowDB 轻量级 JSON 本地数据库

1、作为轻量级的本地存储方式,对于构建不依赖服务器的小型项目,用LowDB存储和管理数据是十分理想的选择。在Nodejs, Electron and browser等一些小型项目中经常能看到LowDB的身影。

2、

3、 const FileSync= require('lowdb/adapters/FileSync');//有多种适配器可选择

4、 const adapter= new FileSync('db.json');//申明一个适配器

5、 db.defaults({posts: [], user:{}, count: 0})

6、.push({id: 1, title:'lowdb is awesome'})

7、 db.set('user.name','typicode')

8、运行程序会在项目中添加db.json文件,里面存储了添加的数据:

9、 lowdb是基于lodash构建的,所以可以使用任何lodash强大的函数,比如: _.get()和 _.find(),并且可以串联地使用:

10、 low(adapter)返回一个具有特定属性和功能的 lodash chain

11、 db.[...].write()/.value()写/读数据

12、 db.getState()/.setState()获取/设置数据库的状态

13、 db._数据库lodash的实例,可以利用这个添加自己的函数或者第三方的mixins,比如lodash-id

14、针对lowdb自带的适配器:FileSync、FileAsync和 LocalBrowser,有以下可选参数:

15、 defaultValue:文件不存在时的默认值;

16、 serialize/deserialize:写之前和读之后的操作。

17、 const adapter= new FilSync('db.json',{

18、 serialize:(data)=> encrypt(JSON.stringify(data)),

19、 deserialize:(data)=> JSON.parse(decrypt(data))

20、可以直接使用lodash的函数进行查询。需要注意的是有些操作可能会导致原数据被修改,为了避免这种误操作,需要使用.cloneDeep(),操作都是惰性的,只有调用.value()或.write()后才会正式执行。

21、可以使用 shortid和 lodash-id为数据库中的每一条记录创建唯一的id索引,然后通过id检索操作记录:

22、 const shortid= require('shortid')

23、.push({ id: shortid.generate(), title:'low!'})

24、 const lodashId= require('lodash-id')

25、 const FileSync= require('lowdb/adapters/FileSync')

26、 const adapter= new FileSync('db.json')

27、// We need to set some default values, if the collection does not exist yet

28、// We also can store our collection

29、//...and retrieve it using its id

30、// Should return data(object or array) or a Promise

31、// Should return nothing or a Promise

32、 const adapter= new MyStorage(args)

33、==============================================

34、 Lowdb 3 is a pure ESM package. If you're having trouble importing it in your project, please read this.

35、 You can use TypeScript to type check your data.

36、 You can also add lodash or other utility libraries to improve lowdb.

37、 For CLI, server and browser usage, see examples/ directory.

38、 Lowdb has two classes(for asynchronous and synchronous adapters).

39、 Calls adapter.read() and sets db.data.

40、 Note: JSONFile and JSONFileSync adapters will set db.data to null if file doesn't exist.

41、 Calls adapter.write(db.data).

42、 Holds your db content. If you're using the adapters coming with lowdb, it can be any type supported by JSON.stringify.

43、 Adapters for reading and writing JSON files.

44、 In-memory adapters. Useful for speeding up unit tests.

45、 Synchronous adapter for window.localStorage.

46、 Adapters for reading and writing text. Useful for creating custom adapters.

47、 If you've published an adapter for lowdb, feel free to create a PR to add it here.

48、 You may want to create an adapter to write db.data to YAML, XML, encrypt data, a remote storage,...

49、 An adapter is a simple class that just needs to expose two methods:

50、 For example, let's say you have some async storage and want to create an adapter for it:

51、 See src/adapters/ for more examples.

52、 To create an adapter for another format than JSON, you can use TextFile or TextFileSync.

53、 Lowdb doesn't support Node's cluster module.

54、 If you have large JavaScript objects(~10-100MB) you may hit some performance issues. This is because whenever you call db.write, the whole db.data is serialized using JSON.stringify and written to storage.

55、 Depending on your use case, this can be fine or not. It can be mitigated by doing batch operations and calling db.write only when you need it.

56、 If you plan to scale, it's highly recommended to use databases like PostgreSQL or MongoDB instead.

二、怎么在mysql中放入json数据

我们知道,JSON是一种轻量级的数据交互的格式,大部分NO SQL数据库的存储都用JSON。MySQL从5.7开始支持JSON格式的数据存储,并且新增了很多JSON相关函数。MySQL 8.0又带来了一个新的把JSON转换为TABLE的函数JSON_TABLE,实现了JSON到表的转换。

mysql> set@ytt='{"name":[{"a":"ytt","b":"action"},{"a":"dble","b":"shard"},{"a":"mysql","b":"oracle"}]}';Query OK, 0 rows affected(0.00 sec)

mysql> select json_keys(@ytt);+-----------------+| json_keys(@ytt)|+-----------------+| ["name"]|+-----------------+1 row in set(0.00 sec)

mysql> select json_keys(@ytt,'$.name[0]');+-----------------------------+| json_keys(@ytt,'$.name[0]')|+-----------------------------+| ["a","b"]|+-----------------------------+1 row in set(0.00 sec)

我们使用MySQL 8.0的JSON_TABLE来转换@ytt。

mysql> select* from json_table(@ytt,'$.name[*]' columns(f1 varchar(10) path'$.a', f2 varchar(10) path'$.b')) as tt;

再来一个复杂点的例子,用的是EXPLAIN的JSON结果集。

set@json_str1='{"query_block":{"select_id": 1,"cost_info":{"query_cost":"1.00"},"table":{"table_name":"bigtable","access_type":"const","possible_keys": ["id" ],"key":"id","used_key_parts": ["id" ],"key_length":"8","ref": ["const" ],"rows_examined_per_scan": 1,"rows_produced_per_join": 1,"filtered":"100.00","cost_info":{"read_cost":"0.00","eval_cost":"0.20","prefix_cost":"0.00","data_read_per_join":"176"},"used_columns": ["id","log_time","str1","str2" ]}}}';

mysql> select json_keys(@json_str1) as'first_object';+-----------------+| first_object|+-----------------+| ["query_block"]|+-----------------+1 row in set(0.00 sec)

mysql> select json_keys(@json_str1,'$.query_block') as'second_object';+-------------------------------------+| second_object|+-------------------------------------+| ["table","cost_info","select_id"]|+-------------------------------------+1 row in set(0.00 sec)

mysql> select json_keys(@json_str1,'$.query_block.table') as'third_object'\G*************************** 1. row***************************third_object: ["key","ref","filtered","cost_info","key_length","table_name","access_type","used_columns","possible_keys","used_key_parts","rows_examined_per_scan","rows_produced_per_join"]1 row in set(0.01 sec)

mysql> select json_extract(@json_str1,'$.query_block.table.cost_info') as'forth_object'\G*************************** 1. row***************************forth_object:{"eval_cost":"0.20","read_cost":"0.00","prefix_cost":"0.00","data_read_per_join":"176"}1 row in set(0.00 sec)

SELECT* FROM JSON_TABLE(@json_str1,

a1_1 varchar(100) PATH'$.key',

a1_2 varchar(100) PATH'$.ref[0]',

a1_3 varchar(100) PATH'$.filtered',

nested path'$.cost_info'

a2_1 varchar(100) PATH'$.eval_cost',

a2_2 varchar(100) PATH'$.read_cost',

a2_3 varchar(100) PATH'$.prefix_cost',

a2_4 varchar(100) PATH'$.data_read_per_join'

a3 varchar(100) PATH'$.key_length',

a4 varchar(100) PATH'$.table_name',

a5 varchar(100) PATH'$.access_type',

a6 varchar(100) PATH'$.used_key_parts[0]',

a7 varchar(100) PATH'$.rows_examined_per_scan',

a8 varchar(100) PATH'$.rows_produced_per_join',

a9 varchar(100) PATH'$.key'

NESTED PATH'$.cost_info'

b1_1 varchar(100) path'$.query_cost'

+-------+------+-------+--------+------+------+------+------+------+----------+-------+------+------+------+------+------+------+

| rowid| a1_1| a1_2| a1_3| a2_1| a2_2| a2_3| a2_4| a3| a4| a5| a6| a7| a8| a9| b1_1| c|

+-------+------+-------+--------+------+------+------+------+------+----------+-------+------+------+------+------+------+------+

| 1| id| const| 100.00| 0.20| 0.00| 0.00| 176| 8| bigtable| const| id| 1| 1| id| NULL| 1|

| 1| NULL| NULL| NULL| NULL| NULL| NULL| NULL| NULL| NULL| NULL| NULL| NULL| NULL| NULL| 1.00| 1|

+-------+------+-------+--------+------+------+------+------+------+----------+-------+------+------+------+------+------+------+

当然,JSON_table函数还有其他的用法,我这里不一一列举了,详细的参考手册。

三、php下如何将json格式的数据直接存入mysql数据库

1、在PHP中,json格式的数据本质上是字符串。当你使用json_encode将数组转换为json字符串时,可以看到这种形式:echo json_encode($array);//输出为{[aaa:bbb,ccc:ddd]}。这里,数组被编码成了一个json字符串,但其内部结构与原始数组有所不同。

2、要将这种json格式的数据直接存入MySQL数据库,首先需要确保你的数据库表中有一个字段能够存储这种格式的数据,例如jsonData。接下来,你可以直接使用这个字段名,将json字符串作为值插入到数据库中。例如:

3、insert into table123(jsonData) values("$myJsonData");

4、这里的$keyJsonData代表你的json字符串,确保它已经被正确地编码并赋值。值得注意的是,在实际使用中,为了防止SQL注入,建议使用预处理语句。例如:

5、$stmt=$pdo->prepare("insert into table123(jsonData) values(:jsonData)");

6、$stmt->execute([':jsonData'=>$myJsonData]);

7、这样不仅可以提高安全性,还能更灵活地处理各种数据类型。此外,确保你的表字段类型支持存储json格式,通常可以使用TEXT或LONGTEXT类型来存储这种数据。

8、在实际应用中,你可能还需要考虑如何从数据库中读取和解析这些json数据。例如,你可以使用json_decode函数将存储的json字符串转换回PHP数组或对象,以便进一步处理。这提供了很大的灵活性,允许你在数据库中存储复杂的数据结构,同时保持代码的简洁性和可维护性。