트리 - Go에서 동적이거나 알려지지 않은 JSON/YAML을 처리하기 위한 간단한 구조
소개
Go는 표준 map[string]interface{} 등을 사용하여 동적 json/yaml을 구문 분석할 수 있습니다. 그러나 중첩된 인터페이스{}는 보기 흉한 코드를 생성하는 경향이 있습니다.
Tree은 이 문제에 대한 한 가지 해결책입니다.
특징
Go의 예
마샬링 및 언마샬링
func ExampleMarshalJSON() {
    group := tree.Map{
        "ID":     tree.ToValue(1),
        "Name":   tree.ToValue("Reds"),
        "Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
    }
    b, err := json.Marshal(group)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(b))
    // Output:
    // {"Colors":["Crimson","Red","Ruby","Maroon"],"ID":1,"Name":"Reds"}
}
func ExampleUnmarshalJSON() {
    data := []byte(`[
  {"Name": "Platypus", "Order": "Monotremata"},
  {"Name": "Quoll",    "Order": "Dasyuromorphia"}
]`)
    var animals tree.Array
    err := json.Unmarshal(data, &animals)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%+v\n", animals)
    // Output:
    // [map[Name:Platypus Order:Monotremata] map[Name:Quoll Order:Dasyuromorphia]]
}
얻다
func ExampleGet() {
    group := tree.Map{
        "ID":     tree.ToValue(1),
        "Name":   tree.ToValue("Reds"),
        "Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
        "Nil":    nil,
    }
    fmt.Println(group.Get("Colors").Get(1))
    fmt.Println(group.Get("Colors", 2))
    fmt.Println(group.Get("Colors").Get(5).IsNil())
    fmt.Println(group.Get("Nil").IsNil())
    // Output:
    // Red
    // Ruby
    // true
    // true
}
찾다
func ExampleFind() {
    group := tree.Map{
        "ID":     tree.ToValue(1),
        "Name":   tree.ToValue("Reds"),
        "Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
    }
    rs, err := group.Find(".Colors[1:3]")
    if err != nil {
        log.Fatal(err)
    }
    for _, r := range rs {
        fmt.Println(r)
    }
    // Output:
    // Red
    // Ruby
}
편집하다
func ExampleEdit() {
    var group tree.Node = tree.Map{
        "ID":     tree.ToValue(1),
        "Name":   tree.ToValue("Reds"),
        "Colors": tree.ToArrayValues("Crimson", "Red", "Ruby", "Maroon"),
    }
    if err := tree.Edit(&group, ".Colors += \"Pink\""); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Append Pink to Colors:\n  %+v\n", group)
    if err := tree.Edit(&group, ".Name = \"Blue\""); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Set Blue to Name:\n  %+v\n", group)
    if err := tree.Edit(&group, ".Colors ^?"); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Delete Colors:\n  %+v\n", group)
    // Output:
    // Append Pink to Colors:
    //   map[Colors:[Crimson Red Ruby Maroon Pink] ID:1 Name:Reds]
    // Set Blue to Name:
    //   map[Colors:[Crimson Red Ruby Maroon Pink] ID:1 Name:Blue]
    // Delete Colors:
    //   map[ID:1 Name:Blue]
}
tq
tq는 이식 가능한 명령줄 JSON/YAML 프로세서입니다. 자세한 내용은 jarxorg/tree을 참조하십시오.
용법
tq is a command-line JSON/YAML processor.
Usage:
  tq [flags] [query] ([file...])
Flags:
  -e, --edit stringArray       edit expression
  -x, --expand                 expand results
  -h, --help                   help for tq
  -U, --inplace                update files, inplace
  -i, --input-format string    input format (json or yaml)
  -O, --output string          output file
  -o, --output-format string   output format (json or yaml, default json)
  -r, --raw                    output raw strings
  -s, --slurp                  slurp all results into an array
  -t, --template string        golang text/template string
  -v, --version                print version
Examples:
  % echo '{"colors": ["red", "green", "blue"]}' | tq '.colors[0]'
  "red"
  % echo '{"users":[{"id":1,"name":"one"},{"id":2,"name":"two"}]}' | tq -x -t '{{.id}}: {{.name}}' '.users'
  1: one
  2: two
  % echo '{}' | tq -e '.colors = ["red", "green"]' -e '.colors += "blue"' .
  {
    "colors": [
      "red",
      "green",
      "blue"
    ]
  }
                Reference
이 문제에 관하여(트리 - Go에서 동적이거나 알려지지 않은 JSON/YAML을 처리하기 위한 간단한 구조), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mojatter/tree-a-simple-structure-for-dealing-with-dynamic-or-unknown-jsonyaml-in-go-4cnn텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)