douxuanpa8298 2018-06-26 05:30
浏览 106
已采纳

在Golang中从stdin读取json对象

How to read a json object from stdin? I want to copy and paste a json object into the stdin, read it and unmarshal it. Here is the code:

    var input string
    _, err := fmt.Scan(&input)
    if err != nil {
        fmt.Println(err)
        continue
    }

    var record MedicalRecord
    if err := json.Unmarshal([]byte(input), &record); err != nil {
        log.Println(err)
        continue
    }

And the errors are printed to console.

> 2018/06/26 00:26:32 invalid character ':' after top-level value
> 2018/06/26 00:26:32 unexpected end of JSON input
> 2018/06/26 00:26:32 invalid character ':' after top-level value
> 2018/06/26 00:26:32 invalid character ',' after top-level value
> 2018/06/26 00:26:32 invalid character ':' after top-level value
> 2018/06/26 00:26:32 invalid character ',' after top-level value
> 2018/06/26 00:26:32 invalid character ':' after top-level value
> 2018/06/26 00:26:32 invalid character ',' after top-level value
> 2018/06/26 00:26:32 invalid character ':' after top-level value
> 2018/06/26 00:26:32 invalid character ',' after top-level value

If I'm not mistaken, Go is reading until it finds ' ' . How can I solve this problem?

  • 写回答

2条回答 默认 最新

  • duanchu7271 2018-06-26 06:15
    关注

    Use a *json.Decoder to consume JSON from an io.Reader:

    package main
    
    import (
        "encoding/json"
        "log"
        "os"
    )
    
    type MedicalRecord struct{}
    
    func main() {
        var record MedicalRecord
    
        err := json.NewDecoder(os.Stdin).Decode(&record)
        if err != nil {
            log.Fatal(err)
        }
    }
    

    You can consume multiple consecutive JSON documents by calling Decode repeatedly:

    package main
    
    import (
        "encoding/json"
        "io"
        "log"
        "os"
    )
    
    type MedicalRecord struct{}
    
    func main() {
        var record MedicalRecord
    
        dec := json.NewDecoder(os.Stdin)
        for {
            err := dec.Decode(&record)
            if err == io.EOF {
                return
            }
            if err != nil {
                log.Fatal(err)
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了
  • ¥20 firefly-rk3399上启动卡住了
  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥15 中级微观经济学,生产可能性边界问题
  • ¥15 TCP传输时不同网卡传输用时差异过大
  • ¥15 请各位看看我写的属于什么算法,或者有更正确的写法?