How should I correctly parse this data in to a struct to avoid the "expression expected" error/warning and successfully build the JSON?

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

How should I correctly parse this data in to a struct to avoid the "expression expected" error/warning and successfully build the JSON?

问题

我正在使用Go编写一个测试程序,它接收5个输入,并将其转换为JSON,然后将其返回给调用者。

JSON结构在我外部定义,所以我无法简化它,尽管我认为它需要简化,所以我只能处理这个烦人的负载结构。

问题是,我无法正确解析/初始化它。它一直抱怨"expected expression",我无法弄清楚原因。

值得注意的是,我不得不使用其中一个JSON到结构体生成器,因为我无法弄清楚结构体应该是什么样子,然后我试图稍微整理一下。可能有一个我没有注意到的错误。

json

{
    "outer": [
        {
            "inner": {
                "key1": "...",
                "key2": "...",
                "key3": "...",
                "key4": "...",
                "key5": "..."
            }
        }
    ]
}

structs

type Payload struct {
	Outer []struct {
		Inner InnerTestData `json:"inner"`
	} `json:"outer"`
}

type InnerTestData struct {
	Alertname   string `json:"key1"`
	QueueInHrs  string `json:"key2"`
	QueueOutHrs string `json:"key3"`
	Urgency     string `json:"key4"`
	Impact      string `json:"key5"`
}

code

func main() {
	if len(os.Args) != 5 {
		fmt.Println("ERROR: There should be 5 args")
		os.Exit(1)
	}

	key1 := os.Args[1]
	key2 := os.Args[2]
	key3 := os.Args[3]
	key4 := os.Args[4]
	key5 := os.Args[5]

	innerTestData := InnerTestData{
		Alertname:   key1,
		QueueInHrs:  key2,
		QueueOutHrs: key3,
		Urgency:     key4,
		Impact:      key5,
	}

	payload := Payload{
		Outer: []struct{
			Inner: innerTestData,
		}{
			Inner: innerTestData,
		},
	}
}

我只是困惑于如何将其解析为Payload结构体,我尝试了我能想到的每种组合,但都没有成功。我意识到这可能是一个简单的错误,但是必须创建一个完全匹配JSON负载的结构体的整个情况过于复杂和令人困惑。

任何帮助将不胜感激。谢谢。

英文:

I'm writing a test program in Go, which takes 5 inputs and will marshal it to JSON and then return it back to the caller.

The JSON structure is defined externally to me so I'm unable to simplify it - even though I reckon it needs it - so I just have to deal with the annoying structure of the payload.

Trouble is, I cannot get it to parse/initialise correctly at all. It keeps complaining about "expected expression" and I can't work out why.

It's worth noting that I had to use one of those JSON-to-struct generators as I couldn't work out what the struct should actually look like, then I tried to clean it up a bit. There could be an error here I'm not seeing.

json

{
    "outer": [
        {
            "inner": {
                "key1": "...",
                "key2": "...",
                "key3": "...",
                "key4": "...",
                "key5": "..."
            }
        }
    ]
}

structs

type Payload struct {
	Outer []struct {
		Inner InnerTestData `json:"inner"`
	} `json:"outer"`
}

type InnerTestData struct {
	Alertname   string `json:"key1"`
	QueueInHrs  string `json:"key2"`
	QueueOutHrs string `json:"key3"`
	Urgency     string `json:"key4"`
	Impact      string `json:"key5"`
}

code

func main() {
	if len(os.Args) != 5 {
		fmt.Println("ERROR: There should be 5 args")
		os.Exit(1)
	}

	key1 := os.Args[1]
	key2 := os.Args[2]
	key3 := os.Args[3]
	key4 := os.Args[4]
	key5 := os.Args[5]

	innerTestData := InnerTestData{
		Key1: key1,
		Key2: key2,
		Key3: key3,
		Key4: key4,
		Key5: key5,
	}

	payload := Payload{
		Outer: []struct{
			Inner: innerTestData,
		},
	}
}

I'm just confused as to how I should actually be parsing this in to the Payload struct, I've tried every combination I can think of without any luck. I'm aware this is probably something simple going wrong, but the whole having to create a struct that perfectly matches the JSON payload situation is really over-complicated and confusing, I find.

Any help appreciated. Cheers.

答案1

得分: 2

使用以下复合字面量:

payload := Payload{
    Outer: []struct {
        Inner InnerTestData `json:"inner"`
    }{
        {Inner: innerTestData},
    },
}

请注意,内部结构变量的复合字面量必须用 {} 包围。

具有匿名结构类型的复合字面量很冗长。在字面量中必须重复类型。可以通过使用命名类型替换匿名类型来简化。

type Outer struct {  // <-- 新的命名类型
    Inner InnerTestData `json:"inner"`
}

type Payload struct {
    Outer []Outer `json:"outer"` // <-- 在这里使用它
}

具有命名类型的复合字面量为:

payload := Payload{
    Outer: []Outer{
        {Inner: innerTestData},
    },
}

编译器会报告 Outer: []struct{ Inner: innerTestData, } 的错误,因为编译器期望在 struct 关键字后面跟着一个结构定义。

英文:

Use the following composite literal:

payload := Payload{
	Outer: []struct {
		Inner InnerTestData `json:&quot;inner&quot;`
	}{
		{Inner: innerTestData},
	},
}

Note that the composite literal for the inner struct variable must be surrounded by {}.

A composite literal with an anonymous struct type is verbose. The type must be repeated in the literal. Simplify by replacing the anonymous type with a named type.

type Outer struct {  // &lt;-- new named type
	Inner InnerTestData `json:&quot;inner&quot;`
}

type Payload struct {
	Outer []Outer `json:&quot;outer&quot;` // &lt;-- use it here
}

The composite literal with the named type is:

payload := Payload{
	Outer: []Outer{
		{Inner: innerTestData},
	},
}

The compiler reports an error for Outer: []struct{ Inner: innerTestData, } because the compiler expects a struct definition following the struct keyword.

huangapple
  • 本文由 发表于 2022年2月5日 08:37:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/70994383.html
匿名

发表评论

匿名网友

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

确定