go数据类型转换

现在的 GO 写法#

go:
BODY := "[{\"customerCode\": \"str12345\", \"deliveryId\":\"str67890\"}]"
request.SetBody([]byte(BODY))

希望用键值对的形式写,由于不会用 go 写,用 php 样例写一个#

php:
$body = [['customerCode' => 'str12345', 'deliveryId' => 'str67890']]
$body = json_encode($body);
Http:post($url, $body)

希望将上面的 go 写成像 php 这样的键值对的写法,因为字符串多了,转义看着眼花,不方便操作.#

最佳答案

用 map 应该比较符合你的需求

    //原始
    BODY := "[{\"customerCode\": \"str12345\", \"deliveryId\":\"str67890\"}]"
    fmt.Println("原始", BODY)

    //反引号
    BODY = `[{"customerCode": "str12345", "deliveryId":"str67890"}]`
    fmt.Println("反引号", BODY)

    //map
    bMap := []map[string]string{{"customerCode": "str12345", "deliveryId": "str67890"}}
    bBODY, _ := json.Marshal(bMap)
    BODY = string(bBODY)
    fmt.Println("map", BODY)

    //map format
    bMap := []map[string]string{{
        "customerCode": "str12345",
        "deliveryId":   "str67890",
    }}
    bBODY, _ := json.Marshal(bMap)
    BODY = string(bBODY)
    fmt.Println("map", BODY)
2年前 评论
讨论数量: 3

是打算把数据转为 json 吗?转 json 用 encoding/json 这个包,这样 data, err := json.Marshal(src)

2年前 评论
deatil (作者) 2年前

用 map 应该比较符合你的需求

    //原始
    BODY := "[{\"customerCode\": \"str12345\", \"deliveryId\":\"str67890\"}]"
    fmt.Println("原始", BODY)

    //反引号
    BODY = `[{"customerCode": "str12345", "deliveryId":"str67890"}]`
    fmt.Println("反引号", BODY)

    //map
    bMap := []map[string]string{{"customerCode": "str12345", "deliveryId": "str67890"}}
    bBODY, _ := json.Marshal(bMap)
    BODY = string(bBODY)
    fmt.Println("map", BODY)

    //map format
    bMap := []map[string]string{{
        "customerCode": "str12345",
        "deliveryId":   "str67890",
    }}
    bBODY, _ := json.Marshal(bMap)
    BODY = string(bBODY)
    fmt.Println("map", BODY)
2年前 评论