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

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}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵