解决了,包名为extract
输入data.json
{
"a": 2,
"b": 3,
"c": {
"d": false
}
}
main.go
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
jsoniter "github.com/json-iterator/go"
)
// Extract 提取JSON
func Extract(extractType string, inputFileName string, keys []string) ([]byte, error) {
content, err := ioutil.ReadFile(inputFileName)
var inputJSON interface{}
var pickJSON map[string]interface{}
if err := jsoniter.Unmarshal(content, &inputJSON); err != nil {
panic(err)
}
if extractType == "pick" {
if err := jsoniter.Unmarshal([]byte("{}"), &pickJSON); err != nil {
panic(err)
}
}
if m, ok := inputJSON.(map[string]interface{}); ok {
for _, key := range keys {
if extractType == "omit" {
if _, exists := m[key]; exists {
delete(m, key)
}
} else {
pickJSON[key] = m[key]
}
}
}
var output []byte
if extractType == "omit" {
output, err = jsoniter.Marshal(inputJSON)
} else {
output, err = jsoniter.Marshal(pickJSON)
}
return output, err
}
func main() {
pluginsKeys := os.Getenv("PLUGIN_KEYS")
extractType := os.Getenv("PLUGIN_TYPE")
inputFileName := os.Getenv("PLUGIN_FILENAME")
outputFileName := os.Getenv("PLUGIN_OUTPUT")
keys := strings.Split(pluginsKeys, ",")
if extractType == "" {
extractType = "omit"
}
if outputFileName == "" {
outputFileName = "result.json"
}
output, err := Extract(extractType, inputFileName, keys)
if err != nil {
panic(err)
}
err = ioutil.WriteFile(outputFileName, output, 0777)
if err != nil {
panic(err)
}
fmt.Println(string(output))
}
测试,编译好后执行
PLUGIN_TYPE=omit PLUGIN_FILENAME=data.json PLUGIN_KEYS=a,b extract
输出
{"c":{"d":false}}