在Golang中从stdin读取json对象

时间:2018-06-26 05:30:59

标签: json string go stdin

如何从stdin读取json对象? 我想将json对象复制并粘贴到stdin中,读取并解组。 这是代码:

    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
    }

并将错误打印到控制台。

> 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

如果我没记错的话,Go会一直阅读直到找到'\ n'为止。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:5)

使用*json.Decoder从io.Reader使用JSON:

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)
    }
}

您可以通过重复调用Decode来使用多个连续的JSON文档:

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 :(得分:2)

调用json.Unmarshal时,您应该拥有完整的JSON对象,否则,您将试图解组一些对解析器没有意义的部分对象。

  • 从stdin读入一个缓冲区,该缓冲区足够容纳整个JSON对象。
  • 解组JSON对象

例如:

package main

import (
    "bytes"
    "io"
    "fmt"
    "os"
    "bufio"
    "encoding/json"
)


func main() {

    var buf bytes.Buffer
    reader := bufio.NewReader(os.Stdin)

    for {
        line, err := reader.ReadString('\n')
        if err != nil {
            if err == io.EOF {
                buf.WriteString(line)
                break // end of the input
            } else {
                fmt.Println(err.Error())
                os.Exit(1) // something bad happened
            }   
        }   
        buf.WriteString(line)

    }   

    fmt.Printf("valid json? %v\n", json.Valid(buf.Bytes()))

    type MedicalRecord struct {
        Name string `json:"name"`
        Age int `json:"age"`
    }   

    var record MedicalRecord
    err := json.Unmarshal(buf.Bytes(), &record)
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1) // something bad happened
    }   

    fmt.Printf("name: %s, age: %d\n", record.Name, record.Age)
}