-1

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

file.json:

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

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

0

2 Answers 2

4

What you have is not a single JSON object but a series of (unrelated) JSON objects. You can't use json.Unmarshal() to unmarshal something that contains multiple (independent) JSON values.

Use json.Decoder to decode multiple JSON values (objects) from a source one-by-one.

For example:

func main() {
    f := strings.NewReader(file)
    dec := json.NewDecoder(f)

    for {
        var job struct {
            Job string `json:"job"`
        }
        if err := dec.Decode(&job); err != nil {
            if err == io.EOF {
                break
            }
            panic(err)
        }
        fmt.Printf("Decoded: %+v\n", job)
    }
}

const file = `{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}`

Which outputs (try it on the Go Playground):

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

This solution works even if your JSON objects take up multiple lines in the source file, or if there are multiple JSON objects in the same line.

See related: I was getting output of exec.Command output in the following manner. from that output I want to get data which I needed

Sign up to request clarification or add additional context in comments.

Comments

0

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

Output:

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

Example

2 Comments

That's fragile as it hinges on the two facts: 1) there will ever be no differently-formatted JSON object which would have a line break as part of any whitespace block; 2) there will ever be no line break embedded in a string literal containing in a JSON object. Hence I'm with @icza on this.
This also breaks if a single line contains multiple JSON objects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.