Skip to content

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

@cblach

Description

@cblach

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions