Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 在字符串中插入变量_Json_Go_Struct - Fatal编程技术网

Json 在字符串中插入变量

Json 在字符串中插入变量,json,go,struct,Json,Go,Struct,我有hostname和json格式化字符串。我想在json格式化字符串中的键的值字符串中插入hostname 我的完整代码: func pager() string { token := "xxxxxxxxxxx" url := "https://api.pagerduty.com/incidents" hostname, err := os.Hostname() fmt.Println(hostname, err) jsonStr := []byte(`{ "incident": {

我有
hostname
json
格式化字符串。我想在
json
格式化字符串中的键的值字符串中插入
hostname

我的完整代码:

func pager() string {
token := "xxxxxxxxxxx"
url := "https://api.pagerduty.com/incidents"
hostname, err := os.Hostname()
fmt.Println(hostname, err)

jsonStr := []byte(`{
    "incident": {
        "type": "incident",
        **"title": "Docker is down on."+hostname,**
        "service": {
          "id": "PWIXJZS",
          "type": "service_reference"
        },
        "priority": {
          "id": "P53ZZH5",
          "type": "priority_reference"
        },
        "urgency": "high",
        "incident_key": "baf7cf21b1da41b4b0221008339ff357",
        "body": {
          "type": "incident_body",
          "details": "A disk is getting full on this machine. You should investigate what is causing the disk to fill, and ensure that there is an automated process in place for ensuring data is rotated (eg. logs should have logrotate around them). If data is expected to stay on this disk forever, you should start planning to scale up to a larger disk."
        },
        "escalation_policy": {
          "id": "PT20YPA",
          "type": "escalation_policy_reference"
        }
    }
}`)

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/vnd.pagerduty+json;version=2")
req.Header.Set("From", "shinoda@wathever.com")
req.Header.Set("Authorization", "Token token="+token)

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    panic(err)
}

return resp.Status
}

func main() {
    fmt.Println(pager())

}
我对go不是很熟悉,在python中我可以很容易地做到这一点,但我不知道在golang中如何做到这一点

如果有人能给我解释,我将不胜感激


提前感谢。

在go中创建一个结构来表示json

type 
    Incident struct {
        Type    string `json:"type"`
        Title   string `json:"title"`
        Service struct {
            ID   string `json:"id"`
            Type string `json:"type"`
        } `json:"service"`
        Priority struct {
            ID   string `json:"id"`
            Type string `json:"type"`
        } `json:"priority"`
        Urgency     string `json:"urgency"`
        IncidentKey string `json:"incident_key"`
        Body        struct {
            Type    string `json:"type"`
            Details string `json:"details"`
        } `json:"body"`
        EscalationPolicy struct {
            ID   string `json:"id"`
            Type string `json:"type"`
        } `json:"escalation_policy"`
}
然后做一些类似的事情

hostname,err:=os.Hostname()
if (err !=nil) {
   panic(err)
}
incident:=Incident{ Type: "incident",
                    Title: fmt.Sprintf("Docker is down on %s", hostname),
                    //...etc etc add all other fields

req, err := http.NewRequest("POST", url, json.Marshal(incident))
在structs中声明structs的解决方法似乎有点笨拙(对不起)

另一个答案显示了如何在事件结构内部拆分结构,这是一种更干净的方法

我将把这个答案留在这里,因为它可能对如何以这种方式声明它感兴趣


如果您只调用
json.Unmarshal
,那么这种方法就可以了,但是对于在程序中声明所需的内容,可能不是最好的

,问题就像正确引用字符串一样简单。这应该可以解决您眼前的问题:

jsonStr := []byte(`{
    "incident": {
        "type": "incident",
        "title": "Docker is down on `+hostname+`",
        "service": {
          "id": "PWIXJZS",
          "type": "service_reference"
        },
        "priority": {
          "id": "P53ZZH5",
          "type": "priority_reference"
        },
        "urgency": "high",
        "incident_key": "baf7cf21b1da41b4b0221008339ff357",
        "body": {
          "type": "incident_body",
          "details": "A disk is getting full on this machine. You should investigate what is causing the disk to fill, and ensure that there is an automated process in place for ensuring data is rotated (eg. logs should have logrotate around them). If data is expected to stay on this disk forever, you should start planning to scale up to a larger disk."
        },
        "escalation_policy": {
          "id": "PT20YPA",
          "type": "escalation_policy_reference"
        }
    }
}`)
但正如@vorspring所建议的,更好的方法是使用适当的Go数据结构,并将其封送到JSON。

尝试以下解决方案:

hostname, err := os.Hostname()
if err != nil {
    // handle err
}

indent := fmt.Sprintf(`{
    "incident": {
        "type": "incident",
        "title": "Docker is down on %s",
        "service": {
          "id": "PWIXJZS",
          "type": "service_reference"
        },
        "priority": {
          "id": "P53ZZH5",
          "type": "priority_reference"
        },
        "urgency": "high",
        "incident_key": "baf7cf21b1da41b4b0221008339ff357",
        "body": {
          "type": "incident_body",
          "details": "A disk is getting full on this machine. You should investigate what is causing the disk to fill, and ensure that there is an automated process in place for ensuring data is rotated (eg. logs should have logrotate around them). If data is expected to stay on this disk forever, you should start planning to scale up to a larger disk."
        },
        "escalation_policy": {
          "id": "PT20YPA",
          "type": "escalation_policy_reference"
        }
    }
}`, hostname)
jsonStr := []byte(indent)

基于@vorspring的响应,除非我弄错了,否则您可能希望以稍微不同的方式定义结构,以避免基于您的 一旦初始化并填充了事件所需的属性,就应该能够在对对象执行json.Marshal()之后发布该对象

jsonObject, _ := json.MarshalIndent(someIncident, "", "\t")
如果要在此包之外使用结构,则可能需要将名称更改为大写,以允许导出

type incident struct {
    Type             string           `json:"type"`
    Title            string           `json:"title"`
    Service          service          `json:"service"`
    Priority         priority         `json:"priority"`
    Urgency          string           `json:"urgency"`
    IncidentKey      string           `json:"incident_key"`
    Body             body             `json:"body"`
    EscalationPolicy escalationPolicy `json:"escalation_policy"`
}

type service struct {
    ID   string `json:"id"`
    Type string `json:"type"`
}

type priority struct {
    ID   string `json:"id"`
    Type string `json:"type"`
}

type body struct {
    Type    string `json:"type"`
    Details string `json:"details"`
}

type escalationPolicy struct {
    ID   string `json:"id"`
    Type string `json:"type"`
}
对象的初始化:

someIncident := incident{
    Type:  "SomeType",
    Title: "SomeTitle",
    Service: service{
        ID:   "SomeId",
        Type: "SomeType"},
    Priority: priority{
        ID:   "SomeId",
        Type: "SomeType"},
    Urgency:     "SomeUrgency",
    IncidentKey: "SomeKey",
    Body: body{
        Type:    "SomeType",
        Details: "SomeDetails"},
    EscalationPolicy: escalationPolicy{
        ID:   "SomeId",
        Type: "SomeType"}}

恐怕我不明白你的问题。您似乎在问两件不相关的事情:如何将变量映射到json键,以及如何附加字符串。您遇到了哪些具体问题?将代码格式化为可读性也会有很大帮助。@Flimzy,对不起,我会尽量让我更清楚。“事件”:{“类型”:“事件”,“标题”:“Docker down on”+hostname}在这个字段标题中,我想附加我的变量hostname,但它被解释为一个普通字符串,并且没有打印它的值。这被逐字解释为+hostname,而不是server1.local。我想指出,
os.hostname()
是一个函数。我已经按照您的建议创建了这个结构,但是我发现其他结构没有定义,我不知道为什么。
incident:=incident{Type:“incident”,Title:fmt.Sprintf(“Docker在%s上停机”,主机名),服务{ID:“PZXSH36”,类型:“服务_引用”,},优先级{ID:“P53ZZH5”,类型:“优先级_引用”,},紧急度:“高”,意外键:“BAF7CF21B1DA41B4B021008339FF357”,正文{Type:“事件_正文”,详细信息:“Docker服务停机或容器停止”,},EscalationPolicy{ID:“PI772OH”,键入:“escalation\u policy\u reference”,},}
服务、优先级、正文和EscalationPolicy被标记为未定义。非常感谢,由于您的解释,我能够理解结构的概念。在我创建结构后,我的帖子工作得非常好。
键入服务结构{ID string
json:“ID”`Type string
json:“Type”
}Type priority struct{ID string
json:“ID”
Type string
json:“Type”
详细信息字符串
json:“Details”
}Type升级策略结构{ID string
json:“id“
Type string
json:“Type”
Type事件结构{Type stringjson:“Type”`Title string
json:“Title”
服务
json:“Service”
优先级
json:“Priority”“
Emergency string
json:“Emergency”
IncidentKey string
json:“incident”
Body
json:“Body”
EscalationPolicy EscalationPolicy
json:“escalation\U policy”
}类型主结构{incident incident Event
json:“incident”
}`
someIncident := incident{
    Type:  "SomeType",
    Title: "SomeTitle",
    Service: service{
        ID:   "SomeId",
        Type: "SomeType"},
    Priority: priority{
        ID:   "SomeId",
        Type: "SomeType"},
    Urgency:     "SomeUrgency",
    IncidentKey: "SomeKey",
    Body: body{
        Type:    "SomeType",
        Details: "SomeDetails"},
    EscalationPolicy: escalationPolicy{
        ID:   "SomeId",
        Type: "SomeType"}}