如何在json文档中为现有数据添加新字段?

时间:2018-01-20 18:08:29

标签: json api go

我是Golang的初学者..我创建了一个API,它正在从couchbase中读取数据,但我无法在json文档中编写新字段。编写新数据的代码如下:

func appendDataEndpoint(w http.ResponseWriter,req *http.Request){
    var data map[string]interface{}
    _ = json.NewDecoder(req.Body).Decode(&data)
    fmt.Println(data)
    params := mux.Vars(req)
    str := params["id"]

    message := message{ Student :data["student"].([]struct),//Here is another problem.How to write type of Student since it is referring to another structure."struct" is throwing type error.
                        College :data["college"].(string),
                        CollegeId: data["collegeid"].(string),
                        Hobbies :data["hobbies"].([]string),
                        Firstname: data["firstname"].(string),
                        Address: data["address"].(string),//New field to be inserted
                        Mobile: data["mobile"].(string),//New field to be inserted
    }
    fmt.Println(message.Address)
    _,err:=bucket.Insert(str, message, 0)

    if err!=nil{
        fmt.Println("Error in inserting")
        w.WriteHeader(401)
        w.Write([]byte(err.Error()))
        return
    }
    json.NewEncoder(w).Encode(message)
}

仍有问题。现在更新的代码段是:

    message:=message{
    Student :data["student"].([]Student),//Error still exists here
    College :data["college"].(string),
    CollegeId :data["collegeid"].(string),
    Hobbies :data["hobbies"].([]string),
    Firstname :data["firstname"].(string),
    Add: data["a"].(string),
    Mo: data["m"].(string),
    }
    _,err:=bucket.Insert(str, message, 0)

错误是:

    panic serving [::1]:63648: interface conversion: interface {} is nil, not []main.Student

1 个答案:

答案 0 :(得分:0)

由于您提供的代码不完全可用,所以需要注意一些事项(如果为message结构提供代码呢?):

从客户端收到请求时,您将其解组为map[string]{}interface对象。从那里,您手动构造一个message对象。为什么不构造message对象而不必使用类型断言?您可以尝试这样做:

type Message struct {
    Student []Student `json:"student"`
    College String `json:"college"`
    CollegeId String `json:"collegeid"`
    Hobbies []String `json:"hobbies"`
    FirstName String `json:"firstname"`
    Address String `json:"address"`
    Mobile String `json:"mobile"`
}

type Student struct {
    Name String `json:"name"`
    Qualifications []String `json:"qualifications"`
    Email String `json:"email"`
}

var data Message
if err := json.NewDecoder(req.Body).Decode(&data); err != nil {
    fmt.Println(err)
    return
}

fmt.Println(data)

这也会照顾你遇到困难的student结构。

我建议您阅读this article以开始使用JSON和Go。