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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| package main
import ( "encoding/json" "fmt" "strings" )
const demoJson = `{"widget":{"debug":"on","window":{"title":"Sample Mask Demo","name":"main_window","width":500,"height":500},"image":{"src":"Images/Sun.png","name":"sun1","hOffset":250,"vOffset":250,"telephone":"13800138888","alignment":"center"},"text":{"data":"Click Here","size":36,"phoneNumber":"13800138000","style":"bold","name":"text1","hOffset":250,"vOffset":100,"alignment":"center","onMouseUp":"sun1.opacity = (sun1.opacity / 100) * 90;"}}}`
const JStringSep = "."
const JStringMaxDepth = 10
func main() { var data map[string]interface{} err := json.Unmarshal([]byte(demoJson), &data) if err != nil { panic(err) } _, _ = dfs(getDfsPath(), "", data) res, err := json.Marshal(data) if err != nil { panic(err) } fmt.Println(string(res)) return }
func getDfsPath() (result map[string]string) { result = make(map[string]string, 0) result = map[string]string{ ".widget.image.telephone": "telephone", ".widget.text.phoneNumber": "telephone", } return }
func dfs(searchPath map[string]string, inputPath string, inputData interface{}) (path string, result interface{}) { if split := strings.Split(inputPath, JStringSep); len(split) > JStringMaxDepth { fmt.Printf("深度大于[%d],异常", JStringMaxDepth) path = inputPath result = inputData return }
switch data := inputData.(type) { case bool: return case string: path = inputPath result = data if handler, ok := searchPath[path]; ok { switch handler { case "telephone": result = data[:3] + "****" + data[7:] } return } return case map[string]interface{}: for key, item := range data { path, result = dfs(searchPath, inputPath+JStringSep+key, item) if _, ok := searchPath[path]; ok { data[key] = result } } return case []interface{}: for key, item := range data { path, result = dfs(searchPath, inputPath, item) if _, ok := searchPath[path]; ok { data[key] = result
} } return } return }
|