2014-10-01 89 views
0

我有一個接收JSON圍棋REST服務,我需要編輯JSON,所以我可以做兩個不同的結構REST服務。操縱JSON在Go使用大猩猩

我的結構:

type Interaction struct{ 

DrugName string `json:"drugName"` 
SeverityLevel string `json:"severityLevel"` 
Summary string `json:"summary"` 
} 

type Drug struct { 
Name string `json:"drugName"` 
Dosages []string `json:"dosages"` 
Interactions []Interaction `json:"interactions"` 
} 

例JSON發送:

{"drugName":"foo","dosages":["dos1"],"interactions":[["advil","high","summaryForAdvil"]]} 

REST服務:

func CreateDrug(w http.ResponseWriter, r *http.Request) { 

    //I verified the received JSON by printing out the bytes: 
    bytes, _ := ioutil.ReadAll(r.Body) 
} 

我的目標是在CreateDrug功能做兩個不同的JSONs所以我可以使兩種不同的結構,藥物與互動:

{"drugName":"foo","dosages":["dos1"]} 
{"drugName":"advil", "severityLevel":"high", "summary":"summaryForAdvil"} 

在圍棋,在這個函數,我如何使用收到的JSON到兩個新JSONs?

回答

0

解組請求相匹配的請求的結構的結構體,值複製到已定義的結構,以及編組創建結果。

func CreateDrug(w http.ResponseWriter, r *http.Request) { 

    // Unmarshal request to value matching the structure of the incoming JSON 

    var v struct { 
    DrugName  string 
    Dosages  []string 
    Interactions [][3]string 
    } 
    if err := json.NewDecoder(r.Body).Decode(&v); err != nil { 
    // handle error 
    } 

    // Copy to new struct values. 

    var interactions []Interaction 
    for _, i := range v.Interactions { 
    interactions = append(interactions, Interaction{DrugName: i[0], SeverityLevel: i[1], Summary: i[2]}) 
    } 

    drug := &Drug{Name: v.DrugName, Dosages: v.Dosages, Interactions: interactions} 

    // Marshal back to JSON. 

    data, err := json.Marshal(drug) 
    if err != nil { 
     // handle error 
    } 

    // Do something with data. 
} 

Playground link

(我假設你想與填充在互動領域的藥品單JSON值。如果這不是你想要的,單獨編組藥物和相互作用的值。)

+0

非常有趣的想法,我會盡快嘗試和更新,thx! – bmw0128 2014-10-01 02:53:23

0

您可以使用json.Encoder和輸出多種JSON結構到流,你只需要解碼輸入JSON,這裏有一個簡單的例子:

type restValue struct { 
    Name   string  `json:"drugName"` 
    Dosages  []string `json:"dosages"` 
    Interactions [][3]string `json:"interactions"` 
} 

func main() { 
    d := []byte(`{"drugName":"foo","dosages":["dos1"],"interactions":[["advil","high","summaryForAdvil"]]}`) 
    var v restValue 
    if err := json.Unmarshal(d, &v); err != nil { 
     panic(err) 
    } 
    interactions := make([]Interaction, 0, len(v.Interactions)) 
    for _, in := range v.Interactions { 
     interactions = append(interactions, Interaction{in[0], in[1], in[2]}) 
    } 
    drug := &Drug{Name: v.Name, Dosages: v.Dosages, Interactions: interactions} 
    enc := json.NewEncoder(os.Stdout) 
    // if you want the whole Drug struct 
    enc.Encode(drug) 

    // or if you want 2 different ones: 
    drug = &Drug{Name: v.Name, Dosages: v.Dosages} 
    enc.Encode(drug) 
    for _, in := range interactions { 
     enc.Encode(in) 
    } 
} 

playground

+0

這看起來不錯,我不知道如果我現在還是不考,但我會得到它肯定在一段時間。我會接受第一個答案,因爲我只是測試了它。 thx尋求幫助 – bmw0128 2014-10-01 03:54:35