在Go中表示JSON策略

huangapple go评论92阅读模式
英文:

representing JSON policy in Go

问题

我想让你做我的中文翻译,代码部分不要翻译, 只返回翻译好的部分, 不要有别的内容。以下是要翻译的内容:

我想生成这个JSON策略:

{"Statement":[{"Resource":"RESOURCE","Condition":{"DateLessThan":{"AWS:EpochTime":EXPIRES}}}]}

下面显示的解决方案生成以下JSON:

{"Statement":{"Resource":"example.com","Condition":{"DateLessThan":{"AWS:EpochTime":"1234543"}}}}

我如何更改这个,使得"Statement"具有数组值?

package main 
import ( 
        "json" 
        "fmt" 
) 

type S struct { 
        Statement []Statement 
} 

type Statement struct { 
        Resource  string 
        Condition Date 
} 

type Date struct { 
        DateLessThan AWS 
} 

type AWS struct { 
        EpochTime string "AWS:EpochTime" 
} 

func main() { 
        expires := "1234543" 
        resource := "example.com" 
        date := &AWS{EpochTime: expires} 
        date2 := &Date{DateLessThan:*date} 
        reso := &Statement{Resource: resource, Condition: *date2} 
        statement := &S{Statement: []Statement{*reso}} 
        result1, _ := json.Marshal(statement) 
        fmt.Printf(result1) 
}
英文:

I would like to Generate this JSON policy:

{"Statement":[{"Resource":"RESOURCE","Condition":{"DateLessThan":{"AWS:EpochTime":EXPIRES}}}]}

The solution I'm showing below produces the following JSON:

{"Statement":{"Resource":"example.com","Condition":{"DateLessThan":{"AWS:EpochTime":"1234543"}}}}

How do I change this so that "Statement": has an array value?

package main 
import ( 
        "json" 
        "fmt" 
) 

type S struct { 
        Statement Statement 
} 

type Statement struct { 
        Resource  string 
        Condition Date 
} 

type Date struct { 
        DateLessThan AWS 
} 

type AWS struct { 
        EpochTime string "AWS:EpochTime" 
} 

func main() { 
        expires := "1234543" 
        resource := "example.com" 
        date := &AWS{EpochTime: expires} 
        date2 := &Date{DateLessThan:*date} 
        reso := &Statement{Resource: resource, Condition: *date2} 
        statement := &S{Statement: *reso} 
        result1, _ := json.Marshal(statement) 
        fmt.Printf(result1) 
} 

答案1

得分: 2

应用以下更改:

type S struct { 
    Statement []Statement 
}
...
    s_array := []Statement{*reso}
    statement := &S{Statement: s_array}

希望这样能更清楚:你想要一个Statement对象的切片,而不仅仅是一个单独的Statement。

英文:

Apply the following changes:

type S struct { 
    Statement []Statement 
}
...
    s_array := []Statement{*reso}
    statement := &S{Statement: s_array}

Hopefully that should make it clear: you want a slice of Statement objects, rather than just a single Statement.

huangapple
  • 本文由 发表于 2011年1月19日 08:39:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/4730634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定