Skip to content
Allen edited this page May 28, 2020 · 1 revision

English | 中文

json-iterator provides several serialization/deserialization options for configuration.

Configure the options

To configure serialization/deserialization options, you need to create a Config structure and enable/disable the options by setting its fields. Then you need to call its Froze method to generate the API interface, which is needed to call the serialization/deserialization function corresponding to your configuration options.

api := jsoniter.Config{SortMapKeys:true}.Froze()
api.Marshal(data)

Here we create a Config with the SortMapKeys option enabled and generate its corresponding API object for serialization

Built-in configuration

json-iterator provides three built-in configurations:

  • ConfigDefault

    ConfigDefault is the default configuration, it enables the EscapeHTML option. If you do not create your own Config object and generate an API object, but directly call the package level functions like jsoniter.xxx, actually you are using this ConfigDefault configuration

  • ConfigCompatibleWithStandardLibrary

    ConfigCompatibleWithStandardLibrary enables EscapeHTML, SortMapKeys and ValidateJsonRawMessage options. You can use this configuration if you need to ensure that your serialization/deserialization behavior 100% compatible with encoding/json

  • ConfigFastest

    ConfigFastest disables EscapeHTML, and enables MarshalFloatWith6Digits and ObjectFieldMustBeSimpleString options. This configuration will let you get the highest performance

Option description

  • IndentionStep

    Set the amount of space indentation when formatting serialized output

    type Student struct{
        Name string
        Age int
        Height float32
    }
    
    // Formatted output with four spaces indentation
    c := jsoniter.Config{IndentionStep:4}.Froze()
    if s, err := c.MarshalToString(Student{"Allen", 18, 180.43}); err == nil{
        fmt.Println(s)
        // Output:
        // {
        //     "Name": "Allen",
        //     "Age": 18,
        //     "Height": 180.43
        // }
    }
  • MarshalFloatWith6Digits

    Specify up to 6 decimal places when serializing floating-point numbers

    c := jsoniter.Config{MarshalFloatWith6Digits:true}.Froze()
    if s, err := c.MarshalToString(3.14159265358979); err == nil{
        fmt.Println(s)
        // Output:
        // 3.141593
    }
  • EscapeHTML

    With this option enabled, if your string type variable contains special characters used in HTML (such as '<', '>', '&', etc.), they will be escaped when serializing

    type Text struct{
        Html string
    }
    
    c := jsoniter.Config{EscapeHTML:true}.Froze()
    if s, err := c.MarshalToString(Text{`<script>xxx</script>`}); err == nil{
        fmt.Println(s)
        // Output:
        // {"Html":"\u003cscript\u003exxx\u003c/script\u003e"}
    }
  • SortMapKeys

    Sort the map type by its key when serializing

    rgb := map[string][3]int{
        "yellow":{255, 255, 0},
        "red":{0, 0, 255},
        "green":{0, 255, 0},
        "blue":{0, 0, 255},
    }
    c := jsoniter.Config{SortMapKeys:true}.Froze()
    if s, err := c.MarshalToString(rgb); err == nil{
        fmt.Println(s)
        // Sort the output in lexicographic order by key
        // Output:
        // {"blue":[0,0,255],"green":[0,255,0],"red":[0,0,255],"yellow":[255,255,0]}
    }
  • UseNumber

    Parse numbers (integers, floats) into json.Number type when deserializing.

    var number interface{}
    c := jsoniter.Config{UseNumber:true}.Froze()
    if err := c.UnmarshalFromString(`3.14159265358979`, &number); err == nil{
        if n, ok := number.(json.Number); ok{
            // The number is parsed into json.Number type
            f, _ := n.Float64()
            fmt.Println(f)
            // Output:
            // 3.14159265358979
        }
    }
  • DisallowUnknownFields

    With this option enabled, if the parser meets an unknown field, that is, a field that cannot be found in the definition of the struct, the parser will not skip it and continue to parse but return an error

    type Student struct{
        Name string
        Age int
        Height float32
    }
    
    var std Student
    c := jsoniter.Config{DisallowUnknownFields:true}.Froze()
    // Unknown field "Weight"
    if err := c.UnmarshalFromString(`{"Name":"Allen","Age":18,"Height":180.43,"Weight":60.56}`, &std); err == nil{
        fmt.Println(std)
    }else{
        fmt.Println(err)
        // Output
        // main.Student.ReadObject: found unknown field: Weight, error found in #10 byte of ...|3,"Weight":60.56}|..., bigger context ...|{"Name":"Allen","Age":18,"Height":180.43,"Weight":60.56}|...
    }
  • TagKey

    Set the tag string, default tag is "json"

    type Student struct{
        Name string `jsoniter:"name"`
        Age int
        Height float32 `jsoniter:"-"`
    }
    
    // Set tag to "jsoniter"
    c := jsoniter.Config{TagKey:"jsoniter"}.Froze()
    if s, err := c.MarshalToString(Student{"Allen", 18, 180.43}); err == nil{
        fmt.Println(s)
        // Output:
        // {"name":"Allen","Age":18}
    }
  • OnlyTaggedField

    With this option enabled, only structure fields with tags will be serialized

    type Student struct{
        Name string `json:"name"`
        Age int
        Height float32 `json:",omitempty"`
    }
    
    c := jsoniter.Config{OnlyTaggedField:true}.Froze()
    if s, err := c.MarshalToString(Student{"Allen", 18, 180.43}); err == nil{
        fmt.Println(s)
        // Age field has no tag and will not be serialized
        // Output:
        // {"name":"Allen","Height":180.43}
    }
  • ValidateJsonRawMessage

    Fields whose type are json.RawMessage will be output intact when serializing. With this option enabled, json-iterator will check whether the json.RawMessage type field is valid json or not. If it is valid, it will be output as is; otherwise it will be encoded as "null"

    type Book struct{
        Pages int
        Name string
        Description json.RawMessage
    }
    
    c := jsoniter.Config{ValidateJsonRawMessage:true}.Froze()
    if s, err := c.MarshalToString(Book{361, "X",json.RawMessage(`{"Category":`)}); err == nil{
        fmt.Println(s)
        // "Description" is an illegal json string, which means it will be encoded as null
        // Output:
        // {"Pages":361,"Name":"X","Description":null}
    }
  • ObjectFieldMustBeSimpleString

    With this option enabled, json-iterator assumes that string type fields in your json do not contain any special character that needs to be unescaped, this option is used to accelerate the speed of the parser

    type Student struct{
        Name string
        Age int
        Height float32
    }
    
    var std Student
    c := jsoniter.Config{ObjectFieldMustBeSimpleString:true}.Froze()
    if err := c.UnmarshalFromString(`{"Name":"Allen","Ag\u0065":18,"Height":180.43}`, &std); err == nil{
        fmt.Println(std)
        // Age field contains escaped characters and they will not be handled 
        // with ObjectFieldMustBeSimpleString option enabled
        // Output:
        // {Allen 0 180.43}
    }
  • CaseSensitive

    With this option enabled, case of the field in the json should be consistent with what they are defined in your struct

    type Student struct{
        Name string
        Age int
        Height float32
    }
    
    var std Student
    c := jsoniter.Config{CaseSensitive:true}.Froze()
    if err := c.UnmarshalFromString(`{"Name":"Allen","Age":18,"height":180.43}`, &std); err == nil{
        fmt.Println(std)
        // The case of the Height field is inconsistent and cannot be parsed correctly
        // Output:
        // {Allen 18 0}
    }