如何创建一个嵌套字典来发送数据?

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

How to create a nested dictionary to post data?

问题

{
"data": {
"payload": {
"from": {
"phone_number": "+XXXXXXXXXX"
},
"to": {
"phone_number": "+XXXXXXXXXX"
}
}
}
}

我正在尝试创建一个嵌套字典作为请求体。我尝试使用struct,但结果不如预期,并且在使用map[string]interface{}{}时出现错误。

  1. 结构体 Route:
type Payload struct {
    From struct {
        PhoneNumber string `json:"phone_number"`
    }
    To struct {
        PhoneNumber string `json:"phone_number"`
    }
}

type Response struct {
    Data struct {
        Payload Payload `json:"payload"`
    }
}

func main() {
    // 其他代码

    payload := Payload{
        From: struct{ PhoneNumber string }{PhoneNumber: sender},
        To:   struct{ PhoneNumber string }{PhoneNumber: recipient},
    }
    response := Response{
        Data: struct{ Payload Payload }{Payload: payload},
    }
    fmt.Println(response)
}

上述代码的输出结果为:

{{{{+XXXXXXXXXX} {+XXXXXXXXXX}}}}

  1. 创建原始字典:
var payload = map[string]interface{}{
    "from": map[string]string{
        "phone_number": sender,
    },
    "to": map[string]string{
        "phone_number": recipient,
    },
}
fmt.Println(payload)

var response = map[string]interface{}{
    "data": map[string]interface{}{
        "payload": payload,
    },
}

错误信息: 无法将类型为map[string]interface{}的'payload'用作类型为string的值。

如果你能指导我正确的方向,我将非常感激。

英文:
{
    "data": {
        "payload": {
            "from": {
                "phone_number": "+XXXXXXXXXX"
            },

            "to": {
                "phone_number": "+XXXXXXXXXX",
			},
        }
    }
}

I'm trying to create a nested dictionary for the post body. I've tried using struct but it didn't work as I expected and while using the map[string]interface{}{} I'm getting an error.

  1. Struct Route:

type Payload struct {
	From struct {
		PhoneNumber string `json:"phone_number"`
	}
	To  struct {
		PhoneNumber string `json:"phone_number"`
	}
}


type Response struct {
	Data struct {
		Payload Payload `json:"payload"`
	}
}


func main() {
  // extra code

  payload := Payload{
		From: struct {PhoneNumber string `json:"phone_number"`}(struct{ PhoneNumber string }{PhoneNumber: sender}),
		To: struct {PhoneNumber string `json:"phone_number"`}(struct{ PhoneNumber string }{PhoneNumber: recipient})}
	response := Response{Data: struct {
		Payload Payload `json:"payload"`
	}(struct{ Payload Payload }{Payload: payload})}
  fmt.Println(response)
}

The above response is:

{{{{+XXXXXXXXXX} {+XXXXXXXXXX}}}}

  1. Raw dict creation:
var payload = map[string]interface{}{}
payload["from"].(map[string]string)["phone_number"] = sender
payload["to"].(map[string]string)["phone_number"] = recipient
fmt.Println(payload)

var response = map[string]interface{}{}
response["data"].(map[string]string)["payload"] = payload

Error: Cannot use 'payload' (type map[string]interface{}) as the type string

I would highly appreciate it if you could guide me in the correct direction

答案1

得分: 2

最简单的方法是使用JSON转Go结构体,生成一个类似的结构体:

type AutoGenerated struct {
	Data Data `json:"data"`
}
type From struct {
	PhoneNumber string `json:"phone_number"`
}
type To struct {
	PhoneNumber string `json:"phone_number"`
}
type Payload struct {
	From From `json:"from"`
	To   To   `json:"to"`
}
type Data struct {
	Payload Payload `json:"payload"`
}

然后可以使用以下示例:

outStruct := AutoGenerated{
	Data: Data{
		Payload: Payload{
			From: From{PhoneNumber: sender},
			To:   To{PhoneNumber: recipient},
		},
	},
}
out, err := json.Marshal(outStruct)
fmt.Println(string(out), err)

这将输出:

{"data":{"payload":{"from":{"phone_number":"234234"},"to":{"phone_number":"32434"}}}} <nil>
英文:

The simplest way is to use the Convert JSON to Go struct, that generate a struct like:

type AutoGenerated struct {
	Data Data `json:&quot;data&quot;`
}
type From struct {
	PhoneNumber string `json:&quot;phone_number&quot;`
}
type To struct {
	PhoneNumber string `json:&quot;phone_number&quot;`
}
type Payload struct {
	From From `json:&quot;from&quot;`
	To   To   `json:&quot;to&quot;`
}
type Data struct {
	Payload Payload `json:&quot;payload&quot;`
}

and use, as example:

outStruct := AutoGenerated{
	Data: Data{
		Payload: Payload{
			From: From{PhoneNumber: sender},
			To:   To{PhoneNumber: recipient},
		},
	},
}
out, err := json.Marshal(outStruct)
fmt.Println(string(out), err)

this will out

{&quot;data&quot;:{&quot;payload&quot;:{&quot;from&quot;:{&quot;phone_number&quot;:&quot;234234&quot;},&quot;to&quot;:{&quot;phone_number&quot;:&quot;32434&quot;}}}} &lt;nil&gt;

答案2

得分: 1

这是你的代码的一个工作示例。当你尝试创建一个原始的映射时,我认为你给nil映射赋值了一个值,这就是为什么你会得到错误的原因。

package main

import (
	"encoding/json"
	"fmt"
)

type (
	Response struct {
		Data Data `json:"data"`
	}

	Data struct {
		PayLoad PayLoad `json:"payload"`
	}

	PayLoad struct {
		From Address `json:"from"`
		To   Address `json:"to"`
	}

	Address struct {
		PhoneNumber string `json:"phone_number"`
	}
)

func main() {
	payload := PayLoad{
		From: Address{PhoneNumber: "+1xxxxxxxxx"},
		To:   Address{PhoneNumber: "+1xxxxxxxxx"},
	}

	resp := Response{
		Data: Data{
			PayLoad: payload,
		},
	}

	j, _ := json.Marshal(resp)
	fmt.Println(string(j))

	// with map

	var payloadNew = map[string]interface{}{
		"from": map[string]interface{}{
			"phone_number": "+1xxxxxxxx",
		},
		"to": map[string]interface{}{
			"phone_number": "+1yyyyyyyy",
		},
	}

	var responseNew = map[string]interface{}{
		"data": map[string]interface{}{
			"payload": payloadNew,
		},
	}

	j, _ = json.Marshal(responseNew)
	fmt.Println(string(j))
}

JSON输出为:

{"data":{"payload":{"from":{"phone_number":"+1xxxxxxxxx"},"to":{"phone_number":"+1xxxxxxxxx"}}}}
{"data":{"payload":{"from":{"phone_number":"+1xxxxxxxx"},"to":{"phone_number":"+1yyyyyyyy"}}}}
英文:

Here is a working example of your code. When you were trying to create a raw map I think you were assigning value to nil map that's why you were getting error.

package main

import (
	&quot;encoding/json&quot;
	&quot;fmt&quot;
)

type (
	Response struct {
		Data Data `json:&quot;data&quot;`
	}

	Data struct {
		PayLoad PayLoad `json:&quot;payload&quot;`
	}

	PayLoad struct {
		From Address `json:&quot;from&quot;`
		To   Address `json:&quot;to&quot;`
	}

	Address struct {
		PhoneNumber string `json:&quot;phone_number&quot;`
	}
)

func main() {
	payload := PayLoad{
		From: Address{PhoneNumber: &quot;+1xxxxxxxxx&quot;},
		To:   Address{PhoneNumber: &quot;+1xxxxxxxxx&quot;},
	}

	resp := Response{
		Data: Data{
			PayLoad: payload,
		},
	}

	j, _ := json.Marshal(resp)
	fmt.Println(string(j))

	// with map

	var payloadNew = map[string]interface{}{
		&quot;from&quot;: map[string]interface{}{
			&quot;phone_number&quot;: &quot;+1xxxxxxxx&quot;,
		},
		&quot;to&quot;: map[string]interface{}{
			&quot;phone_number&quot;: &quot;+1yyyyyyyy&quot;,
		},
	}

	var responseNew = map[string]interface{}{
		&quot;data&quot;: map[string]interface{}{
			&quot;payload&quot;: payloadNew,
		},
	}

	j, _ = json.Marshal(responseNew)
	fmt.Println(string(j))
}

The json outputs are:

{&quot;data&quot;:{&quot;payload&quot;:{&quot;from&quot;:{&quot;phone_number&quot;:&quot;+1xxxxxxxxx&quot;},&quot;to&quot;:{&quot;phone_number&quot;:&quot;+1xxxxxxxxx&quot;}}}}
{&quot;data&quot;:{&quot;payload&quot;:{&quot;from&quot;:{&quot;phone_number&quot;:&quot;+1xxxxxxxx&quot;},&quot;to&quot;:{&quot;phone_number&quot;:&quot;+1yyyyyyyy&quot;}}}}

huangapple
  • 本文由 发表于 2021年8月30日 15:27:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/68980328.html
匿名

发表评论

匿名网友

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

确定