New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
cblach opened this Issue Aug 30, 2018 · 2 comments

Comments

Projects
None yet
4 participants
@cblach

cblach commented Aug 30, 2018

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.

@gopherbot gopherbot added this to the Proposal milestone Aug 30, 2018

@gopherbot gopherbot added the Proposal label Aug 30, 2018

@meirf

This comment has been minimized.

Member

meirf commented Oct 14, 2018

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 rsc added the Proposal-Hold label Oct 17, 2018

@rsc

This comment has been minimized.

Contributor

rsc commented Oct 17, 2018

On hold for JSON sweep.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment