从字符串

时间:2017-08-01 06:10:05

标签: string go

我想将字符串发送到server.My字符串如下所示

  str := "[{\"name\":\"cpu\",\"status\":\"%d\"}, {\"name\":\"LTE\",\"status\":\"%d\"}, {\"name\":\"Network\",\"status\":\"%d\"}, {\"name\":\"Memory\",\"status\":\"%d\"}]"

当我使用“fmt.Println(str)”打印时,它会提供如下所需的输出,

[{"name":"cpu","status":"%d"}, {"name":"LTE","status":"%d"}, {"name":"Network","status":"%d"}, {"name":"Memory","status":"%d"}]

但是当我向服务器发送相同的字符串时,服务器会收到如下字符串,

"[{\"name\":\"cpu\",\"status\":\"%d\"}, {\"name\":\"LTE\",\"status\":\"%d\"}, {\"name\":\"Network\",\"status\":\"%d\"}, {\"name\":\"Memory\",\"status\":\"%d\"}]"

请在下面找到我的代码段:

func (m *MetricSet) Fetch() (common.MapStr, error) {
        var x string
        x =fmt.Sprintf("[{\"name\":\"cpu\",\"status\":\"%d\"}, {\"name\":\"LTE\",\"status\":\"%d\"}, {\"name\":\"Network\",\"status\":\"%d\"}, {\"name\":\"Memory\",\"status\":\"%d\"}]", 17,26,34,33)
        fmt.Println(x)
        event := common.MapStr{
                "cpu_status": (m.cpu_status%4),
                "memory_status" : (m.memory_status%4),
                "lte_status" : (m.lte_status%4),
                "network_status" : (m.network_status%4),
                "summary": x,
        }

        m.cpu_status++
        m.memory_status = m.memory_status + 2
        m.lte_status = m.lte_status + 7
        m.network_status = m.network_status + 13

        return event, nil
}

如何解决?请帮帮我。

2 个答案:

答案 0 :(得分:1)

您正在将摘要内容作为字符串发送,因此您需要将其作为一张地图发送

k := [...]common.MapStr{
    {"name": "cpu", "status": m.cpu_status},
    {"name": "LTE", "status": m.lte_status},
    {"name": "Network", "status": m.network_status},
    {"name": "Memory", "status": m.memory_status},
}
event := common.MapStr{
    "cpu_status":     (m.cpu_status % 4),
    "memory_status":  (m.memory_status % 4),
    "lte_status":     (m.lte_status % 4),
    "network_status": (m.network_status % 4),
    "summary":        k,
}

请参阅https://play.golang.org/p/yTSXnNKclG

答案 1 :(得分:1)

event编组为JSON时,如果summary包含双引号,则event的值将被转义。 快速而肮脏的解决方案map[string]interface{}定义为summary,以便能够将任意类型存储为地图值,并将event := map[string]interface{}{ "cpu_status": (m.cpu_status%4), "memory_status" : (m.memory_status%4), "lte_status" : (m.lte_status%4), "network_status" : (m.network_status%4), "summary": json.RawMessage(x), } 值存储为{{ 3}}例如

x

但是,您需要确保summary的值是有效的JSON对象(这很容易出错)。更强大的解决方案是将type Status struct { Name string `json:"name"` Status string `json:"status"` } summary := []*Status{ &Status{"cpu", "17"}, &Status{"LTE", "26"}, &Status{"Network", "34"}, &Status{"Memory", "33"}, } event := map[string]interface{}{ "cpu_status": (m.cpu_status%4), "memory_status" : (m.memory_status%4), "lte_status" : (m.lte_status%4), "network_status" : (m.network_status%4), "summary": summary, } 中的项定义为结构类型,例如

document.getElementsByName("sortIcon").src="images/pic.jpg";