-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathjson.go
63 lines (52 loc) · 1.34 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package clover
import (
"bufio"
"encoding/json"
"os"
d "github.com/ostafen/clover/v2/document"
"github.com/ostafen/clover/v2/query"
)
// ExportCollection exports an existing collection to a JSON file.
func (db *DB) ExportCollection(collectionName string, exportPath string) error {
exists, err := db.HasCollection(collectionName)
if err != nil {
return err
}
if !exists {
return ErrCollectionNotExist
}
result, err := db.FindAll(query.NewQuery(collectionName))
if err != nil {
return err
}
docs := make([]map[string]interface{}, 0)
for _, doc := range result {
docs = append(docs, doc.AsMap())
}
jsonString, err := json.Marshal(docs)
if err != nil {
return err
}
return os.WriteFile(exportPath, jsonString, os.ModePerm)
}
// ImportCollection imports a collection from a JSON file.
func (db *DB) ImportCollection(collectionName string, importPath string) error {
file, err := os.Open(importPath)
if err != nil {
return err
}
if err := db.CreateCollection(collectionName); err != nil {
return err
}
reader := bufio.NewReader(file)
jsonObjects := make([]*map[string]interface{}, 0)
err = json.NewDecoder(reader).Decode(&jsonObjects)
if err != nil {
return err
}
docs := make([]*d.Document, 0)
for _, doc := range jsonObjects {
docs = append(docs, d.NewDocumentOf(*doc))
}
return db.Insert(collectionName, docs...)
}