使用NewEncoder的嵌套JSON流

I am wondering whether it is possible to stream JSON and include other (sibling) keys besides the stream itself? I would like to include some extra data about the generated file. Something like the following:

{
    "info": {
        "department": "a",
        "id": "1",
    },
    "members": [
        { "name": "a", "age": "1" },
        { "name": "b", "age": "2" },
        { "name": "c", "age": "3" },
        ...stream
    ]
}

Currently, I stream JSON to a flat file like so:

package main

import (
    "encoding/json"
    "os"
)

type Member struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    enc := json.NewEncoder(os.Stdout)

    letters := []string{"a", "b", "c", "d", "e", "f"}

    for i, letter := range letters {
        key := Member{letter, i}

        var err = enc.Encode(&key)
        if err != nil {
            // handle err
        }
    }
}

But as indicated above I would like to add another key such as "info" and contain the stream in a key such as "members"

I can think of a solution to the problem, which would store them as separate files in a directory, e.g.

directory
├─ members.json
└─ info.json

But could other (sibling) keys be added or am I limited to a flat file?

Something similar is possible, but it's not especially simple. I have done something similar in one of my open-source projects in a PR that I have not yet merged. But you can see my example here.

The interface I expose is to take in an io.ReadCloser and return a (possibly manipulated) io.ReadCloser. Internally, it uses a json.Decoder to parse the JSON, possibly adding new data to the stream. I'm not sure how a json.Encoder would fit into this (as asked in your question).

Producing a complete working example for you would be a pretty big task for an SO answer, but I hope the link I provided can point you in the right direction.

This is a case where good unit tests, and a TDD approach, would be well advised!