dpymrcl269187540 2018-06-14 07:53
浏览 56
已采纳

如何使用小写键封送JSON

I use AWS Lambda with DynamoDB using golang.

My DynamoDB table use lowercase attribute names such as id or name.

In Go, if I want to be able to marshal a struct correctly, I have to name fields starting with a capital letter.

type Item struct {
    ID   string
    Name string
}

To put an item into my DynamoDB table, I have to marshal it into a map[string]*dynamodb.AttributeValue, using dynamodbattribute.MarshalMap function.

item := Item{
    ID: "xxxx",
    Name: "yyyy"
}

av, _ := dynamodbattribute.MarshalMap(item)

Of course, this will create a map using names written as ID and Name, which are incompatible with id and name from the dynamodb table.

Reading the documentation, I found that you can use a custom encoder, and enable json tags.

type Item struct {
    ID   string  `json="id"`
    Name string  `json="name"`
}

func setOpts(encoder *dynamodbattribute.Encoder) {
    // Not sure which one I sould set
    // So I set them both :)
    encoder.SupportJSONTags = true
    encoder.MarshalOptions.SupportJSONTags = true
}

func main() {
    encoder := dynamodbattribute.NewEncoder(setOpts)

    encoder.Encode(...)
}

But here the encoder.Encode() method is only used to create a dynamodb.AttributeValue, and not a map[string]*dynamodb.AttributeValue.

Is there a way to use a custom encoder with MarshalMap? Or am I using it in a wrong way?

EDIT:

Okay so as Zak pointed out, there is a dynamodbav tag that can be used.

I also found out that I was using json tags in a wrong way. I should use the syntax json:"id" instead of json="id".

Indeed, DynamoDB SDK uses the json tag if available, and this one can be overrided by the dynamodbav.

So all I had to do was to make my structure looks like this and it worked

type Item struct {
    ID   string  `json:"id"`
    Name string  `json:"name"`
}
  • 写回答

1条回答 默认 最新

  • douzhenggui8171 2018-06-14 12:31
    关注

    Dynamo's built in marshalling, from MarshalMap(...) can support struct tags, similar to json.

    You can add them to the type that you are marshalling, like so:

    type Item struct {
        ID   string `dynamodbav:"id"`
        Name string `dynamodbav:"name"`
    }
    

    See the docs here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?