https://github.com/alimy/tson
Simple JSON content merge.
https://github.com/alimy/tson
go json template
Last synced: 3 months ago
JSON representation
Simple JSON content merge.
- Host: GitHub
- URL: https://github.com/alimy/tson
- Owner: alimy
- License: apache-2.0
- Created: 2019-01-23T07:31:39.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-01-24T03:01:39.000Z (over 7 years ago)
- Last Synced: 2025-08-16T11:16:11.164Z (11 months ago)
- Topics: go, json, template
- Language: Go
- Size: 10.7 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Tson
Tson used to merge JSON content from a json template and a struct type object instance.
#### Prototype
1. Use `tson` that defined in struct's tag string to tag json template info help tson to merge content from struct type object
2. Or use `$.filedNanme` that defined in json template string help tson to merge content from struct type object
3. tson `Parse(...)/ParseFrom(...)` will build a AST tree that contain json segment content
4. tson use parsed `AST` tree merge give struct type object instance content then write result to target io.Writer
5. json template can cached in memory or key-value storage such as Redis
#### Usage
```go
package main
import (
"bytes"
"fmt"
"github.com/alimy/tson"
)
type Issue struct {
Version string `json:"version"`
Bio string `json:"bio"`
}
type Data struct {
Id string `json:"id" tson:"id"`
Name string `json:"name" tson:"name"`
Age uint8 `json:"age" tson:"age"`
Issue *Issue `json:"issue"`
Random []int `json:"random"`
}
type Info struct {
Name string
Alias string
}
func main() {
// merge json content from struct type template
srcData := &Data{
Age: 0,
Issue: &Issue{
Version: "v0.1.0",
Bio: "happy in codding",
},
Random: []int{1, 2, 3, 4, 5},
}
if jsonTmpl, err := tson.New("json").Parse(srcData); err == nil {
buf := bytes.NewBuffer([1024]byte{}[:])
jsonTmpl.Execute(buf, &Data{
Id: "1006013",
Name: "Michael Li",
})
fmt.Println(buf.String())
}
// merge json content from text string template
jsonTmplStr := `{
"name": $.Name,
"alias": $.Alias,
"other": {
"ping": "pong",
},
}`
if jsonTmpl, err := tson.New("tson").ParseFrom(jsonTmplStr); err == nil {
buf := bytes.NewBuffer([1024]byte{}[:])
jsonTmpl.Execute(buf, &Info{
Name: "Micheal Li",
Alias: "Alimy",
})
fmt.Println(buf.String())
}
}
// Output:
// {
// "id": "1006013",
// "name": "Michael Li",
// "age": 0,
// "issue": {
// "version": "v0.1.0",
// "bio": "happy in codding",
// },
// "random": [1, 2, 3, 4, 5],
// }
// {
// "name": "Micheal Li",
// "alias": "Alimy",
// "other": {
// "ping": "pong",
// },
// }
```
#### Status
Project is just a prototype now will add logic implements later.