簡體   English   中英

將Marshall JSON Slice轉換為有效JSON

[英]Marshall JSON Slice to valid JSON

我正在使用Golang構建REST API,但在嘗試正確編組Json Slice時遇到了一些麻煩。 即使在尋找幾個問題和答案以及在網絡上之后,我也已經撓了一下頭。

從本質上講,我有一個客戶端的Redis調用后調用-X GET /todo/吐奶一片todos

[{"content":"test6","id":"46"} {"content":"test5","id":"45"}] //[]string

現在,我想根據是否找到todos來返回給定的Response ,所以我有一個Struct

type Response struct {
    Status string
    Data []string
}

然后,如果我發現了一些todos我只是Marshal用JSON

if(len(todos) > 0){
    res := SliceResponse{"Ok", todos}
    response, _ = json.Marshal(res)
}

而且,為了刪除響應中不必要的\\ ,我使用bytes.Replace

response = bytes.Replace(response, []byte("\\"), []byte(""), -1)

最后,得到

{
   "Status" : "Ok",
   "Data" : [
              "{"content":"test6","id":"46"}",
              "{"content":"test5","id":"45"}"
    ]
}

如您所見,每個{之前和之后}每個" {第一個和最后一個除外)顯然是錯誤的。而正確的JSON將是

{
    "Status": "Ok",
    "Data": [{
        "content ": "test6",
        "id ": "46"
    }, {
        "content ": "test5",
        "id ": "45"
    }]
}

我成功地找到了它們的索引,並使用正則表達式對它們進行了修剪,從而使它們脫穎而出,但我對此感到納悶。

是否有一種干凈,更好的方法來實現這一目標?

只要有可能,您都應該從匹配所需json的對象中進行封送。 我建議從redis解析json:

type Response struct {
    Status string
    Data   []*Info
}

type Info struct {
    Content string `json:"content"`
    ID      string `json:"id"`
}

func main() {
    r := &Response{Status: "OK"}
    for _, d := range data {
        info := &Info{}
        json.Unmarshal([]byte(d), info)
        //handle error
        r.Data = append(r.Data, info)
    }
    dat, _ := json.Marshal(r)
    fmt.Println(string(dat))
}

游樂場鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM