golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.23k stars 17.57k forks source link

proposal: encoding/json: Support for nested values in JSON tags #27366

Open cblach opened 6 years ago

cblach commented 6 years ago

I have often run into situations where it would convenient to translate nested JSON objects into flat structs.

An example would be the AWS dynamodb API that returns nested objects based on the saved type (https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_GetItem.html), i.e.:

 {
    "Item": {
        "somekey": {
            "S": "somestr"
        }
    }
}

Lets say we know we saved "somekey" as a string. Thus it would be convinient, if we could avoid the need for the nested structs:

package main
import(
    "encoding/json"
    "fmt"
)

var str = `
{
    "Item": {
        "somekey": {
            "S": "somestr"
        },
        "otherkey": {
            "N": "123"
        }
    }
}
`

type Data struct {
    Somekey  string`json:"Item.somekey.S"`
    Otherkey uint64`json:"Item.otherkey.N,string"`
}

func main() {
    d := Data{}
    if err := json.Unmarshal([]byte(str), &d); err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Data struct:", d)
}

This allows one to get saner data structures with minimal code, where previously one would have to manually translate the structs to achieve this.

meirf commented 5 years ago

where previously one would have to manually translate the structs to achieve this.

Have you tried https://mholt.github.io/json-to-go? It's obviates the manual translation. Sure, it means you'll have more code in the form of the struct, but that doesn't sound like a concern for you.

If that tool is enough for you?

rsc commented 5 years ago

On hold for JSON sweep.

WhileLoop commented 4 years ago

where previously one would have to manually translate the structs to achieve this.

Have you tried https://mholt.github.io/json-to-go? It's obviates the manual translation. Sure, it means you'll have more code in the form of the struct, but that doesn't sound like a concern for you.

If that tool is enough for you?

This does not work in cases where one is forced to use a flat struct. For example, I am using sqlx to scan database columns into a struct, but want to encode the flat structure as nested JSON. Workaround is to manually map columns to nested nested struct members, but being able to tell the JSON encoder to created nested output using tags directly would be very handy.

ian-fox commented 3 years ago

What is the JSON sweep? I've been meaning to write something like this for a while, either as a standalone package or contributing directly to go.

dsnet commented 3 years ago

This seems like duplicate of #6213, or at least has significant overlap.

felipearomani commented 7 months ago

It could support syntax for JSON Path, as I suggest in my duplicated proposal https://github.com/golang/go/issues/66116.