jsonreplace

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2023 License: MIT Imports: 5 Imported by: 0

README

jsonreplace

This package provides a JSON utility function for replacing values in JSON.

GoDoc Go Report Card License

Overview

This package provides a JSON utility function for replacing values in JSON. It is enabled to replace JSON valuse on matched JSON Schema.

package main

import (
	"encoding/json"
	"log"
	"os"
	"strconv"
	"strings"

	"github.com/mashiike/jsonreplace"
)

func main() {
	v := map[string]string{
		"name": "foo",
		"age":  "30",
	}
	enc := jsonreplace.NewEncoder(os.Stdout)
	mux := jsonreplace.NewReplaceMux()
	mux.ReplaceFunc(`{"type":"string"}`, func(raw json.RawMessage) (json.RawMessage, error) {
		str := strings.Trim(string(raw), `"`)
		num, err := strconv.ParseInt(str, 10, 64)
		if err != nil {
			return raw, nil
		}
		return json.Marshal(num)
	})
	enc.SetReplacer(mux)
	if err := enc.Encode(v); err != nil {
		log.Fatal(err)
	}
	// Output:
	// {"age":30,"name":"foo"}
}

this example replace string value to number value in JSON.

Advance Usage: DefaltReplaceMux

package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/mashiike/jsonreplace"
)

type Person struct {
	Email string `json:"email"`
	Name  string `json:"name"`
	Age   int    `json:"age"`
}

type Organization struct {
	Leader  Person   `json:"leader"`
	Members []Person `json:"members"`
}

func main() {
	org := Organization{
		Leader: Person{
			Email: "admin@example.com",
			Name:  "Tarou Yamada",
			Age:   30,
		},
		Members: []Person{
			{
				Email: "member1@example.com",
				Name:  "Hanako Tanaka",
				Age:   20,
			},
			{
				Email: "member2@exampl.com",
				Name:  "Jhon Smith",
				Age:   25,
			},
		},
	}
	jsonreplace.ReplaceFunc(`{"type":"object","properties":{"age":{"type":"integer"}},"required":["age"]}`, func(raw json.RawMessage) (json.RawMessage, error) {
		var v map[string]interface{}
		if err := json.Unmarshal(raw, &v); err != nil {
			return nil, err
		}
		if num, ok := v["age"].(float64); ok {
			num -= 5
			if num < 20 {
				num = 20
			}
			v["age"] = num
		}
		return json.Marshal(v)
	})
	jsonreplace.ReplaceFunc(`{"type":"string","format":"email"}`, func(raw json.RawMessage) (json.RawMessage, error) {
		return json.RawMessage(`"***********@example.com"`), nil
	})
	bs, err := jsonreplace.MarshalIndent(org, nil, "", "  ")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(bs))
	// Output:
	// {
	//   "leader": {
	//     "email": "***********@example.com",
	//     "name": "Tarou Yamada",
	//     "age": 25
	//   },
	//   "members": [
	//     {
	//       "email": "***********@example.com",
	//       "name": "Hanako Tanaka",
	//       "age": 20
	//     },
	//     {
	//       "email": "***********@example.com",
	//       "name": "Jhon Smith",
	//       "age": 20
	//     }
	//   ]
	// }
}

this example replace email address and age value in JSON. email address masked by ***********@example.com and age value is decreased by 5 and minimum value is 20.

Installation

go get github.com/mashiike/slogutils

License

This project is licensed under the MIT License - see the LICENSE(./LICENCE) file for details.

Contribution

Contributions, bug reports, and feature requests are welcome. Pull requests are also highly appreciated. For more details, please

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrNilEncoder    = errors.New("jsonreplace: nil encoder")
	ErrInvalidSchema = errors.New("jsonreplace: invalid schema")
	ErrNilReplacer   = errors.New("jsonreplace: nil replacer")
	ErrAbortReplacer = errors.New("jsonreplace: abort replacer")
)
View Source
var DefaultReplaceMux = &defaultReplaceMux

DefaultReplaceMux is the default ReplaceMux.

Functions

func Marshal

func Marshal(v interface{}, replacer Replacer) ([]byte, error)

Marshal returns the JSON encoding of v, replacing JSON objects as json.Marshal does.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/mashiike/jsonreplace"
)

type Person struct {
	Email string `json:"email"`
	Name  string `json:"name"`
	Age   int    `json:"age"`
}

type Organization struct {
	Leader  Person   `json:"leader"`
	Members []Person `json:"members"`
}

func main() {
	org := Organization{
		Leader: Person{
			Email: "admin@example.com",
			Name:  "Tarou Yamada",
			Age:   30,
		},
		Members: []Person{
			{
				Email: "member1@example.com",
				Name:  "Hanako Tanaka",
				Age:   20,
			},
			{
				Email: "member2@exampl.com",
				Name:  "Jhon Smith",
				Age:   25,
			},
		},
	}
	jsonreplace.ReplaceFunc(`{"type":"object","properties":{"age":{"type":"integer"}},"required":["age"]}`, func(raw json.RawMessage) (json.RawMessage, error) {
		var v map[string]interface{}
		if err := json.Unmarshal(raw, &v); err != nil {
			return nil, err
		}
		if num, ok := v["age"].(float64); ok {
			num -= 5
			if num < 20 {
				num = 20
			}
			v["age"] = num
		}
		return json.Marshal(v)
	})
	jsonreplace.ReplaceFunc(`{"type":"string","format":"email"}`, func(raw json.RawMessage) (json.RawMessage, error) {
		return json.RawMessage(`"***********@example.com"`), nil
	})
	bs, err := jsonreplace.MarshalIndent(org, nil, "", "  ")
	if err != nil {
		log.Fatal(err)
	}
	var masked Organization
	if err := json.Unmarshal(bs, &masked); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Leader: Name=%s, Email=%s, Age=%d\n", masked.Leader.Name, masked.Leader.Email, masked.Leader.Age)
	for i, member := range masked.Members {
		fmt.Printf("Member%d: Name=%s, Email=%s, Age=%d\n", i+1, member.Name, member.Email, member.Age)
	}
	fmt.Println()
}
Output:

Leader: Name=Tarou Yamada, Email=***********@example.com, Age=25
Member1: Name=Hanako Tanaka, Email=***********@example.com, Age=20
Member2: Name=Jhon Smith, Email=***********@example.com, Age=20

func MarshalIndent

func MarshalIndent(v interface{}, replacer Replacer, prefix, indent string) ([]byte, error)

MarshalIndent is like Marshal but applies Indent to format the output.

func Replace

func Replace(schema string, r Replacer) error

Replace adds a Replacer to the DefaultReplaceMux based on the given JSON schema.

func ReplaceFunc

func ReplaceFunc(schema string, f func(json.RawMessage) (json.RawMessage, error)) error

ReplaceFunc adds a Replacer function to the DefaultReplaceMux based on the given JSON schema.

func Unmarshal

func Unmarshal(data []byte, v interface{}, replacer Replacer) error

Unmarshal is like json.Unmarshal, but execute Unmarshal after replacing JSON objects.

Types

type Decoder

type Decoder struct {
	*json.Decoder
	// contains filtered or unexported fields
}

Decoder is a JSON decoder with replaces JSON objects.

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new Decoder that reads from r.

func (*Decoder) Decode

func (d *Decoder) Decode(v interface{}) error

Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v,

func (*Decoder) SetReplacer

func (d *Decoder) SetReplacer(replacer Replacer)

SetReplacer sets the Replacer.

type Encoder

type Encoder struct {
	*json.Encoder
	// contains filtered or unexported fields
}

Encoder is a JSON encoder with replaces JSON objects.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new Encoder that writes to w.

func (*Encoder) Encode

func (e *Encoder) Encode(v interface{}) error

Encode writes the JSON encoding of v to the stream, replacing JSON objects as json.Encoder does. if not SetReplacer, use DefaultReplaceMux

func (*Encoder) SetReplacer

func (e *Encoder) SetReplacer(r Replacer)

SetReplacer sets the Replacer to use.

type ReplaceMux

type ReplaceMux struct {
	// contains filtered or unexported fields
}

A ReplaceMux is a multiplexer for Replacers.

func NewReplaceMux

func NewReplaceMux() *ReplaceMux

NewReplaceMux returns a new ReplaceMux.

func (*ReplaceMux) Clone

func (mux *ReplaceMux) Clone() *ReplaceMux

Clone returns a clone of the ReplaceMux.

func (*ReplaceMux) NoRecursive

func (mux *ReplaceMux) NoRecursive(flag bool)

NoRecursive sets whether the ReplaceMux should recursively check substructures such as objects and arrays.

func (*ReplaceMux) Replace

func (mux *ReplaceMux) Replace(schema string, r Replacer) error

Replace adds a Replacer to the ReplaceMux based on the given JSON schema.

func (*ReplaceMux) ReplaceFunc

func (mux *ReplaceMux) ReplaceFunc(schema string, f func(json.RawMessage) (json.RawMessage, error)) error

ReplaceFunc adds a Replacer function to the ReplaceMux based on the given JSON schema.

func (*ReplaceMux) ReplaceJSON

func (mux *ReplaceMux) ReplaceJSON(raw json.RawMessage) (json.RawMessage, error)

ReplaceJSON replaces a JSON object with another JSON object based on the JSON schema. It executes the ReplaceJSON function of the Replacer that matches the given JSON schema. It checks the registered JSON schemas in the order they were added. If no JSON schema matches, it recursively checks substructures such as objects and arrays. To turn off recursive checking, call mux.NoRecursive(true).

type Replacer

type Replacer interface {
	ReplaceJSON(json.RawMessage) (json.RawMessage, error)
}

A Replacer replaces a JSON object with another JSON object.

var VoidReplacer Replacer = ReplacerFunc(func(raw json.RawMessage) (json.RawMessage, error) {
	return raw, nil
})

VoidReplacer is a Replacer that does nothing.

type ReplacerFunc

type ReplacerFunc func(json.RawMessage) (json.RawMessage, error)

ReplacerFunc is an adapter to allow the use of ordinary functions as Replacers.

func (ReplacerFunc) ReplaceJSON

func (f ReplacerFunc) ReplaceJSON(bs json.RawMessage) (json.RawMessage, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL