Documentation
¶
Overview ¶
Package jsons is a universal JSON merge library for Go.
Example (Merge) ¶
a := []byte(`{"a":1}`)
b := []byte(`{"b":[1]}`)
c := []byte(`{"b":[2]}`)
d := []byte(`{"c":null}`)
got, err := jsons.Merge(a, b, c, d)
if err != nil {
panic(err)
}
fmt.Println(string(got))
Output: {"a":1,"b":[1,2],"c":null}
Example (MergeAdvanced) ¶
a := []byte(`
{
"log": {"level": "debug"},
"inbounds": [{"tag": "in-1"}],
"outbounds": [{"_order": 100, "tag": "out-1"}],
"route": {"rules": [
{"_tag":"rule1","inbound":["in-1"],"outbound":"out-1"}
]}
}`)
b := []byte(`
{
"log": {"level": "error"},
"outbounds": [{"_order": -100, "tag": "out-2"}],
"route": {"rules": [
{"_tag":"rule1","inbound":["in-1.1"],"outbound":"out-1.1"}
]}
}`)
var m = jsons.NewMerger(
jsons.WithMergeBy("tag"),
jsons.WithMergeByAndRemove("_tag"),
jsons.WithOrderByAndRemove("_order"),
jsons.WithIndent("", " "),
)
got, err := m.Merge(a, b)
if err != nil {
panic(err)
}
fmt.Println(string(got))
Output: { "log": { "level": "error" }, "inbounds": [ { "tag": "in-1" } ], "outbounds": [ { "tag": "out-2" }, { "tag": "out-1" } ], "route": { "rules": [ { "inbound": [ "in-1", "in-1.1" ], "outbound": "out-1.1" } ] } }
Index ¶
- Variables
- func Merge(inputs ...interface{}) ([]byte, error)
- type Format
- type LoadFunc
- type LoadOrderedFunc
- type Merger
- func (m *Merger) Extensions(formatNames ...Format) ([]string, error)
- func (m *Merger) Merge(inputs ...interface{}) ([]byte, error)
- func (m *Merger) MergeAs(format Format, inputs ...interface{}) ([]byte, error)
- func (m *Merger) RegisterLoader(name Format, extensions []string, fn LoadFunc) error
- func (m *Merger) RegisterOrderedLoader(name Format, extensions []string, fn LoadOrderedFunc) error
- type Option
- func WithIndent(prefix, indent string) Option
- func WithMergeBy(name string) Option
- func WithMergeByAndRemove(name string) Option
- func WithOrderBy(name string) Option
- func WithOrderByAndRemove(name string) Option
- func WithPreprocessor(preprocessor PreprocessorFunc) Option
- func WithTypeOverride(override bool) Option
- type OrderedMap
- type PreprocessorFunc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var NewOrderedMap = ordered.New
NewOrderedMap is an alias of ordered.New
Functions ¶
func Merge ¶
Merge merges input JSONs into a single JSON.
The default merger does only simple merging, which means:
- Simple values (string, number, boolean) are overwritten by later ones.
- Container values (object, array) are merged recursively.
Accepted Input:
- string: path to a local file
- []string: paths of local files
- []byte: content of a file
- [][]byte: content list of files
- io.Reader: content reader
- []io.Reader: content readers
If you need complex merging, create a custom merger with options.
Types ¶
type LoadOrderedFunc ¶
type LoadOrderedFunc func([]byte) (*OrderedMap, error)
LoadOrderedFunc load the input bytes to *OrderedMap, which keeps the fields order
type Merger ¶
type Merger struct {
// contains filtered or unexported fields
}
Merger is the json merger
Example (WithPreprocessor) ¶
a := []byte(`{"array": ["ONE", "TWO"]}`)
b := []byte(`{"array": ["THREE"]}`)
m := jsons.NewMerger(jsons.WithPreprocessor(func(key string, value interface{}) interface{} {
if str, ok := value.(string); ok {
switch str {
case "ONE":
return 1
case "TWO":
return 2
case "THREE":
return 3
}
}
return value
}))
got, err := m.MergeAs(jsons.FormatJSON, a, b)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(got))
Output: {"array":[1,2,3]}
func (*Merger) Extensions ¶
Extensions get supported extensions of given formats. If formatNames is empty or contains FormatAuto, it returns all extensions.
func (*Merger) Merge ¶
Merge merges inputs into a single json.
It detects the format by file extension, or try all mergers if no extension found
Accepted Input:
- string: path to a local file
- []string: paths of local files
- []byte: content of a file
- [][]byte: content list of files
- io.Reader: content reader
- []io.Reader: content readers
func (*Merger) MergeAs ¶
MergeAs loads inputs of the specific format and merges into a single json.
Accepted Input:
- string: path to a local file
- []string: paths of local files
- []byte: content of a file
- [][]byte: content list of files
- io.Reader: content reader
- []io.Reader: content readers
func (*Merger) RegisterLoader ¶
RegisterLoader register a new format loader. The fields order is not guaranteed between merges due to the use of map[string]interface{}.
Example ¶
const FormatTOML jsons.Format = "toml"
m := jsons.NewMerger()
m.RegisterLoader(
FormatTOML,
[]string{".toml"},
func(b []byte) (map[string]interface{}, error) {
m := make(map[string]interface{})
// err := toml.Unmarshal(b, &m)
// if err != nil {
// return nil, err
// }
return m, nil
},
)
func (*Merger) RegisterOrderedLoader ¶
func (m *Merger) RegisterOrderedLoader(name Format, extensions []string, fn LoadOrderedFunc) error
RegisterOrderedLoader register a new format loader that loads data into an ordered map, who keeps the fields order between merges.
Example ¶
const FormatYAML jsons.Format = "yaml"
m := jsons.NewMerger()
m.RegisterOrderedLoader(
FormatYAML,
[]string{".yaml", ".yml"},
func(b []byte) (*jsons.OrderedMap, error) {
m := jsons.NewOrderedMap()
// "github.com/goccy/go-yaml" is recommended since it's able to use json.Unmarshaler
// err := yaml.UnmarshalWithOptions(
// b, m,
// yaml.UseJSONUnmarshaler(), // important
// )
// if err != nil {
// return nil, err
// }
return m, nil
},
)
type Option ¶
type Option func(m *Merger)
Option is the option for merger
func WithIndent ¶
WithIndent sets the indent options for merged output.
func WithMergeBy ¶
WithMergeBy is the merge by field for slice sort rule
func WithMergeByAndRemove ¶
WithMergeByAndRemove is the merge by field for slice merge rule
func WithOrderBy ¶
WithOrderBy is the order by field for slice sort rule
func WithOrderByAndRemove ¶
WithOrderByAndRemove is the order by field for slice merge rule
func WithPreprocessor ¶
func WithPreprocessor(preprocessor PreprocessorFunc) Option
WithPreprocessor adds a preprocessor function to preprocess values before merging.
func WithTypeOverride ¶
WithTypeOverride sets whether to override the type when merging.
Example ¶
a := []byte(`{"a":1}`)
b := []byte(`{"a":false}`)
m := jsons.NewMerger(
jsons.WithTypeOverride(true),
)
got, err := m.Merge(a, b)
if err != nil {
panic(err)
}
fmt.Println(string(got))
Output: {"a":false}
type PreprocessorFunc ¶
type PreprocessorFunc func(key string, value interface{}) interface{}
PreprocessorFunc is the type of preprocessor function, which can be used to preprocess values before merging.