jsongo

Round trip encoding of JSON strings with iancoleman/orderedmap


I am trying to encode and decode a JSON string in go. The final string needs to maintain proper encoding of special characters like &, <br>, etc. I am not sure how to do this. Here is what I am trying:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"

    orderedmap "github.com/iancoleman/orderedmap"
)

func main() {
    var testObj = orderedmap.New()
    var str = "{\"\\\" & <br> 😃\": 1}"
    json.Unmarshal([]byte(str), &testObj)
    fmt.Println(str)

    var buf1 bytes.Buffer
    encoder1 := json.NewEncoder(&buf1)
    encoder1.SetEscapeHTML(false)
    encoder1.Encode(testObj)
    newStr1 := string(buf1.Bytes())
    fmt.Println("Not html escaped: " + newStr1)

    var buf2 bytes.Buffer
    encoder2 := json.NewEncoder(&buf2)
    encoder2.SetEscapeHTML(true)
    encoder2.Encode(testObj)
    newStr2 := string(buf2.Bytes())
    fmt.Println("html escaped: " + newStr2)
}

The output is:

{"\" & <br> 😃": 1}
Not html escaped: {"\" \u0026 \u003cbr\u003e 😃":1}

html escaped: {"\" \u0026 \u003cbr\u003e 😃":1}


Program exited.

However, I would like the output to be identical to the input.

Here's a link to the program in the go playground.


Solution

  • You just need to call SetEscapeHTML(false) on your orderedmap itself

    var testObj = orderedmap.New()
    testObj.SetEscapeHTML(false)
    var str = "{\"\\\" & <br> 😃1}"
    json.Unmarshal([]byte(str), &testObj)
    fmt.Println(str)
    

    See this playground

    The output

    {"\" & <br> 😃": 1}
    Not html escaped: {"\" & <br> 😃":1}
    
    html escaped: {"\" \u0026 \u003cbr\u003e 😃":1}
    

    From the official example:

    // use SetEscapeHTML() to whether escape problematic HTML characters or not, defaults is true
        o.SetEscapeHTML(false)