github.com/searKing/golang/go@v1.2.117/encoding/prettyjson/example_test.go (about)

     1  // Copyright 2024 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package prettyjson_test
     6  
     7  import (
     8  	"fmt"
     9  	"os"
    10  
    11  	"github.com/searKing/golang/go/encoding/prettyjson"
    12  )
    13  
    14  func ExampleMarshal() {
    15  	type ColorGroup struct {
    16  		ID        int
    17  		Name      string
    18  		LongName  string
    19  		Colors    []string
    20  		ColorById map[string]string
    21  		Url       string
    22  		LongUrl   string
    23  		Empty     struct {
    24  			ID   int
    25  			Name string
    26  		}
    27  	}
    28  	group := ColorGroup{
    29  		ID:        1,
    30  		Name:      "Reds",
    31  		LongName:  "The quick brown fox jumps over the lazy dog",
    32  		Colors:    []string{"The quick brown fox jumps over the lazy dog", "Crimson", "Red", "Ruby", "Maroon"},
    33  		ColorById: map[string]string{"0": "red", "1": "green", "2": "blue", "3": "while"},
    34  		Url:       "https://example.com/tests/1?foo=1&bar=baz",
    35  		LongUrl:   "https://example.com/tests/1.html?foo=1&bar=baz&a=0&b=1&c=2&d=3#paragraph",
    36  	}
    37  	b, err := prettyjson.Marshal(group,
    38  		prettyjson.WithEncOptsTruncateString(10),
    39  		prettyjson.WithEncOptsTruncateBytes(10),
    40  		prettyjson.WithEncOptsTruncateSliceOrArray(2),
    41  		prettyjson.WithEncOptsTruncateMap(2),
    42  		prettyjson.WithEncOptsTruncateUrl(true),
    43  		prettyjson.WithEncOptsEscapeHTML(false),
    44  		prettyjson.WithEncOptsOmitEmpty(true))
    45  	if err != nil {
    46  		fmt.Println("error:", err)
    47  	}
    48  	_, _ = os.Stdout.Write(b)
    49  
    50  	// Output:
    51  	// {"ID":1,"Name":"Reds","LongName":"The quick ...43 chars","Colors":["The quick ...43 chars","Crimson", "...5 elems"],"ColorById":{"0":"red","1":"green","...4 pairs":"4"},"Url":"https://example.com/tests/1?foo=1&bar=baz","LongUrl":"https://example.com/tests/1.html ...72 chars,6Q9F]"}
    52  }