dsue14118 2016-12-03 17:01
浏览 970
已采纳

Go:JSON输入和JSON意外结束.Unmarshal返回nil值

I'm testing out how to unmarshal a json response from an API I'm using.

The json looks something like the following;

body := []byte(`[
    {"name":"Name1", "value":100.00},
    {"name":"Name2", "value":200.00}
]`)

I've searched around for various ways to do this, but fail to get this to work. The unmarshal returns zero values. I also get an error "unexpected end of JSON input" (I've removed the error handling in the example).

Full code example - https://play.golang.org/p/VMdWuAm6HS

Reference:

  1. https://godoc.org/encoding/json#RawMessage
  2. Golang json Unmarshal "unexpected end of JSON input"
  3. How to unmarshal json into interface{} in golang?
  • 写回答

1条回答 默认 最新

  • drbae3964 2016-12-03 17:17
    关注

    Your input JSON can be modeled with a simple []Obj where Obj is your type:

    type Obj struct {
        Name  string  `json:"name"`
        Value float32 `json:"value"`
    }
    

    Nothing else is required, really:

    body := []byte(`[
        {"name":"Name1", "value":100.00},
        {"name":"Name2", "value":200.00}]`)
    
    var res []Obj
    err := json.Unmarshal(body, &res)
    fmt.Printf("%#v
    %v
    ", res, err)
    

    Output contains the data from the input JSON (try it on the Go Playground):

    []main.Obj{main.Obj{Name:"Name1", Value:100}, main.Obj{Name:"Name2", Value:200}}
    <nil>
    

    Back to your code:

    Where you're going wrong is that you use this model:

    type Obj struct {
        Name string `json:"name"`
        Value float32 `json:"value"`
    }
    
    type Result struct {
        Data json.RawMessage
    }
    
    var res []Result
    

    But this res variable would model the following JSON:

    [
        {"Data":{"name":"Name1", "value":100.00}},
        {"Data":{"name":"Name2", "value":200.00}}
    ]
    

    I think you can see the difference: the elements of the array here are JSON Objects with a "Data" field, which then are modeled with your Obj. This input JSON is then properly parsed with your original parsing code, you can try it on the Go Playground:

    [{{"name":"Name1", "value":100.00}} {{"name":"Name2", "value":200.00}}] 
    &main.Obj{Name:"Name1", Value:100} 
    &main.Obj{Name:"Name2", Value:200}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 matlab有约束条件下的多元函数求最小值
  • ¥50 如何隐藏网页弹出框的url地址栏
  • ¥20 metropolis算法模拟二维ising模型来计算磁化强度,fortran
  • ¥15 uniapp-typescript-vue报错
  • ¥15 oracle强制关机以后报错01033
  • ¥15 给Chat with RTX添加语言模型时遇到问题
  • ¥15 oracle修复,怎么根据日志修复呀?
  • ¥15 使用Stable Diffusion时出现错误
  • ¥15 请教含粗糙度的点接触润滑问题
  • ¥100 需要3万组微信数据,昵称+头像+朋友圈背景