Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected encoding with interface{} key using Canonical and MapKeyAsString. #390

Closed
winder opened this issue Feb 16, 2023 · 0 comments
Closed

Comments

@winder
Copy link

winder commented Feb 16, 2023

Problem statement

When MapKeyAsString and Canonical are true, integer map keys are not quoted.

Expected behavior

Setting MapKeyAsString should ensure all map keys are quoted.

Example

These examples show the unexpected behavior using github.com/ugorji/go/codec v1.2.9.

Snippet

	handle := new(codec.JsonHandle)
	handle.MapKeyAsString = true
	handle.Canonical = true

	var b []byte
	enc := codec.NewEncoderBytes(&b, handle)
	enc.MustEncode(map[interface{}]interface{}{0: "int key"})
	if strings.Contains(string(b), "0:") {
		fmt.Printf("   * ERROR: unquoted key in \"%s\"\n", b)
	}

Standalone program:

package main

import (
	"fmt"
	"strings"

	"github.com/ugorji/go/codec"
)

func test(name string, canonical bool, mapType interface{}) {
	fmt.Printf("* %s, canonical = %t\n", name, canonical)

	handle := new(codec.JsonHandle)
	handle.MapKeyAsString = true
	handle.Canonical = canonical

	var b []byte
	enc := codec.NewEncoderBytes(&b, handle)
	enc.MustEncode(mapType)
	if strings.Contains(string(b), "0:") {
		fmt.Printf("   * ERROR: unquoted key in \"%s\"\n", b)
	}
}

func main() {
	test("map[int]interface{}", true, map[int]interface{}{0: "int key"})
	test("map[int]interface{}", false, map[int]interface{}{0: "int key"})
	test("map[interface{}]interface{}", true, map[interface{}]interface{}{0: "interface{} key"})
	test("map[interface{}]interface{}", false, map[interface{}]interface{}{0: "interface{} key"})
}

Output:

* map[int]interface{}, canonical = true
* map[int]interface{}, canonical = false
* map[interface{}]interface{}, canonical = true
   * ERROR: unquoted key in "{0:"interface{} key"}"
* map[interface{}]interface{}, canonical = false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant