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

问题描述

使用 encoding/json 包可以很容易地解析像下面这样的对象.

[{"东西":"foo"},{别的东西":酒吧"}]

我面临的问题是当有多个像这样从服务器返回的字典时:

{"something":"foo"}{别的东西":酒吧"}

无法使用以下代码解析.

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

我正在尝试解析 Common Crawl 数据(参见 示例).

我该怎么做?

解决方案

假设您的输入确实是一系列有效的 JSON 文档,请使用 json.Decoder 解码它们:

包主进口 (编码/json"fmt"我"日志"字符串")无功输入 = `{"foo": "bar"}{"foo": "baz"}`类型文档结构{Foo 字符串}功能主(){dec := json.NewDecoder(strings.NewReader(input))为了 {var doc 文档错误 := dec.Decode(&doc)如果错误 == io.EOF {//全做完了休息}如果错误!= nil {日志.致命(错误)}fmt.Printf("%+v
", doc)}}

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

如果您的输入确实是您在问题中显示的内容,那么这不是 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).

How can I do this?

解决方案

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
", doc)
    }
}

Playground: https://play.golang.org/p/ANx8MoMC0yq

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 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:02
查看更多