gpt4 book ai didi

json - 深度相等 : Why does an unmarshalled map return DeepEqual() results differently than a seemingly identical literal

转载 作者:IT王子 更新时间:2023-10-29 02:05:10 26 4
gpt4 key购买 nike

我不明白如何比较未编码的 JSON。示例:

package main

import (
"fmt"
"reflect"
"encoding/json"
)

func main() {
a := map[string]interface{} {"foo": 1, "bar": 2}
b := map[string]interface{} {"bar": 2, "foo": 1}
fmt.Printf("Literal B is %v, DeepEqual is %v\n", b, reflect.DeepEqual(a, b))

err := json.Unmarshal([]byte(`{"bar": 2, "foo": 1}`), &b)
if err != nil {
panic("Could not unmarshal")
}
fmt.Printf("Umarshalled B is %v, DeepEqual is %v\n", b, reflect.DeepEqual(a, b))
}

打印

文字 B 是 map[bar:2 foo:1],DeepEqual 是 true

Umarshalled B 是 map[bar:2 foo:1],DeepEqual 是false

从文字初始化的 B 和 JSON 解码后的 B 有什么不同?

最佳答案

这回答了你的问题:

fmt.Printf("%T\n", b["foo"]) // Prints "float64" after unmarshaling.

JSON 数字是 64 位 float ,而您的原始 map 值是整数。来自docs :

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

关于json - 深度相等 : Why does an unmarshalled map return DeepEqual() results differently than a seemingly identical literal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31597873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com