使用多个 json 对象解组 json 文件(无效的 json 文件) [英] unmarshal json file with multiple json object (not valid json file)

查看:42
本文介绍了使用多个 json 对象解组 json 文件(无效的 json 文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下内容的 json 文件 (file.json):

I have a json file (file.json) with following content:

file.json:

{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}

文件内容如上(非有效json文件)

The contents of the file are exactly as above (not valid json file)

我想在我的代码中使用数据,但我不能解组这个

I want use data in my code but I can not Unmarshal This

推荐答案

您可以逐行读取字符串并对其进行解组:

You can read string line by line and unmarshal it:

package main

import (
    "bufio"
    "encoding/json"
    "fmt"
    "strings"
)

type j struct {
    Job string `json:"job"`
}

func main() {
    payload := strings.NewReader(`{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}`)
    fscanner := bufio.NewScanner(payload)
    for fscanner.Scan() {
        var job j
        err := json.Unmarshal(fscanner.Bytes(), &job)
        if err != nil {
            fmt.Printf("%s", err)
            continue
        }
        fmt.Printf("JOB %+v\n", job)
    }
}

输出:

JOB {Job:developer}
JOB {Job:taxi driver}
JOB {Job:police}

示例

这篇关于使用多个 json 对象解组 json 文件(无效的 json 文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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