构建一个具有包含逗号的字段名称的结构体。

huangapple go评论66阅读模式
英文:

Building a struct with a field name which has a comma

问题

我正在尝试根据我收到的响应创建一个基于结构体的结构。我无法控制响应的内容,在其结构中,字段名称中使用逗号作为字段名称本身的一部分。

JSON示例:

        "date": "2022-09-09 00:00:00 UTC",
        "Sum": {
            "Change, %": "0.10",
            "Price": "254",
            "Value, $": "455.26",
            }

当我尝试以“常规”的方式创建结构体时,由于使用逗号字符,reflect.StructTag.Get期望的是特定的内容,而不是名称的其余部分,所以会出现错误。
结构体示例:

Date   string `json:"date"`
Sum	   struct {
	Change	string `json:"Change, %"`
	Price	string `json:"Price"`
	Value   string `json:"Value, $"`
} `json:"Sum"`

我收到的错误信息是:
"struct field tag json:"Value, $"与reflect.StructTag.Get不兼容:结构体标签值中有可疑的空格"

目标是稍后操作和使用这些数据(希望使用简单的名称),因此“仅仅”打印JSON或将其移动到数组或类似选项不能是最终步骤。

'Price'字段按预期工作,但使用逗号的字段存在问题。我找不到解决方法或类似的问题。

希望了解如何处理这个问题。

谢谢!

英文:

I'm trying to create a struct based on a response I get.
I have no control over the response, and in it's structure there are field names which use comma as part of the filed name itself

JSON Example:

        "date": "2022-09-09 00:00:00 UTC",
        "Sum": {
            "Change, %": "0.10",
            "Price": "254",
            "Value, $": "455.26",
            }

When trying to create a struct the "regular" way, I get an error since once I use the comma character, reflect.StructTag.Get expects something specific and not the rest of the name.
Struct Example:

Date   string `json:"date"`
Sum	   struct {
	Change	string `json:"Change, %"`
	Price	string `json:"Price"`
	Value   string `json:"Value, $"`
} `json:"Sum"`

The error I receive is:
"struct field tag json:"Value, $" not compatible with reflect.StructTag.Get: suspicious space in struct tag value"

The goal is to later manipulate and use this data (hopefully using my simple names), so "just" printing the JSON or moving it to an array or similar option cannot be the final step.

The 'Price' field is working as expected, but the problem is with the fields using the comma.
I couldn't find a way around it or a similar question.

Would love to understand how to deal with this issue.

Thanks!

答案1

得分: 1

你可以将Sum JSON对象解组为Go map,并将map中的值分配给结构体字段。限制仅适用于结构体标签(不能包含逗号等任意字符),但是map可以包含任何键。

例如:

type Sum struct {
    Change string
    Price  string
    Value  string
}

func (s *Sum) UnmarshalJSON(data []byte) error {
    var m map[string]string
    if err := json.Unmarshal(data, &m); err != nil {
        return err
    }

    s.Change = m["Change, %"]
    s.Price = m["Price"]
    s.Value = m["Value, $"]
    return nil
}

type model struct {
    Date string `json:"date"`
    Sum  Sum    `json:"Sum"`
}

func main() {
    var m model
    if err := json.Unmarshal([]byte(src), &m); err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", m)
}

const src = `{
  "date": "2022-09-09 00:00:00 UTC",
  "Sum": {
    "Change, %": "0.10",
    "Price": "254",
    "Value, $": "455.26"
  }
}`

这将输出(在Go Playground上尝试):

{Date:2022-09-09 00:00:00 UTC Sum:{Change:0.10 Price:254 Value:455.26}}
英文:

You may unmarshal the Sum JSON object into a Go map, and assign the values from the map to the struct fields. The restriction only applies to struct tags (that they may not contain arbitrary characters like comma), but maps may hold any keys.

For example:

type Sum struct {
	Change string
	Price  string
	Value  string
}

func (s *Sum) UnmarshalJSON(data []byte) error {
	var m map[string]string
	if err := json.Unmarshal(data, &m); err != nil {
		return err
	}

	s.Change = m["Change, %"]
	s.Price = m["Price"]
	s.Value = m["Value, $"]
	return nil
}

type model struct {
	Date string `json:"date"`
	Sum  Sum    `json:"Sum"`
}

func main() {
	var m model
	if err := json.Unmarshal([]byte(src), &m); err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", m)
}

const src = `{
  "date": "2022-09-09 00:00:00 UTC",
  "Sum": {
    "Change, %": "0.10",
    "Price": "254",
    "Value, $": "455.26"
  }
}`

This will output (try it on the Go Playground):

{Date:2022-09-09 00:00:00 UTC Sum:{Change:0.10 Price:254 Value:455.26}}

huangapple
  • 本文由 发表于 2022年9月12日 03:36:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/73682156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定