如何使用Golang解析ndjson文件? [英] How do I parse ndjson file using Golang?

查看:112
本文介绍了如何使用Golang解析ndjson文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ndjson (换行分隔的JSON)文件,我需要对其进行解析并获取用于某些逻辑操作的数据.有什么好的方法可以使用golang解析 ndjson 文件.下面给出了一个示例ndjson

I have a ndjson (newline delimited JSON) file, I need to parse it and get the data for some logical operation. Is there any good method for parsing ndjson files using golang. A sample ndjson is given below

{"a":"1","b":"2","c":[{"d":"100","e":"10"}]}
{"a":"2","b":"2","c":[{"d":"101","e":"11"}]}
{"a":"3","b":"2","c":[{"d":"102","e":"12"}]}

推荐答案

编码/json 解码器根据值类型解析具有可选或必需空格的顺序JSON文档.因为换行符是空格,所以解码器处理 ndjson .

The encoding/json Decoder parses sequential JSON documents with optional or required whitespace depending on the value type. Because newlines are whitespace, the decoder handles ndjson.

d := json.NewDecoder(strings.NewReader(stream))
for {
    // Decode one JSON document.
    var v interface{}
    err := d.Decode(&v)

    if err != nil {
        // io.EOF is expected at end of stream.
        if err != io.EOF {
            log.Fatal(err)
        }
        break
    }

    // Do something with the value.
    fmt.Println(v)
}

在操场上运行.

这篇关于如何使用Golang解析ndjson文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆