在Go中解析多个JSON对象 [英] Parsing multiple JSON objects in Go

查看:155
本文介绍了在Go中解析多个JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用encoding/json包可以很容易地解析如下对象.

Objects like the below can be parsed quite easily using the encoding/json package.

[ 
    {"something":"foo"},
    {"something-else":"bar"}
]

我面临的麻烦是,当从服务器返回多个命令时,像这样:

The trouble I am facing is when there are multiple dicts returned from the server like this :

{"something":"foo"}
{"something-else":"bar"}

无法使用以下代码进行解析.

This can't be parsed using the code below.

correct_format := strings.Replace(string(resp_body), "}{", "},{", -1)
json_output := "[" + correct_format + "]"

我正在尝试解析常见的抓取数据(请参见示例).

I am trying to parse Common Crawl data (see example).

我该怎么做?

推荐答案

假设您的输入确实是一系列有效的JSON文档,请使用

Assuming your input is really a series of valid JSON documents, use a json.Decoder to decode them:

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "log"
    "strings"
)

var input = `
{"foo": "bar"}
{"foo": "baz"}
`

type Doc struct {
    Foo string
}

func main() {
    dec := json.NewDecoder(strings.NewReader(input))
    for {
        var doc Doc

        err := dec.Decode(&doc)
        if err == io.EOF {
            // all done
            break
        }
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("%+v\n", doc)
    }
}

游乐场: https://play.golang.org/p/ANx8MoMC0yq

如果您输入的内容确实是问题中显示的内容,则不是JSON,您必须编写自己的解析器.

If your input really is what you've shown in the question, that's not JSON and you have to write your own parser.

这篇关于在Go中解析多个JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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