我有以下JSON
结构:
{
"Users": [
{
"UserName": "Administrator",
"CreateDate": "2018-01-26T13:07:28Z",
"UserId": "YYYYY",
},
{
"UserName": "test_user1",
"CreateDate": "2018-01-26T14:32:13Z",
"UserId": "XXXXX",
},
]
}
我这样读了这个文件:
jsonIAMUsers = open('reports/1.16-IAM.json', 'r')
IAMUsers = json.load(jsonIAMUsers)
jsonIAMUsers.close()
我是否将每个UserName
字段的值保存到列表中以便迭代它?我的意思是如何将Administrator
和test_user1
放入列表中?
答案 0 :(得分:3)
只需做一个list comprehension!
main()
注意type Slot struct {
f1 int
f2 string
f3 []*string
}
func NewSlot(f1, f2){
return &Slot{f1: f1, f2: f2, f2: make([]*string, 0)}
}
func main() {
slots := &Slots{}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
s := scanner.Text()
sarr := strings.Split(s, " ")
fmt.Println("scanner", slots)
someFunc(slots, sarr[0], sarr[1:]...)
}
}
func someFunc(slots *Slots, cmd string, args ...string) {
slots = NewSlots(5) // return Pointer to slots with 5 and other value initialized
// But not reflecting to main() func, Why?
}
部分。它是context manager,它将为您执行所有与文件相关的例程(关闭等)。
with open('reports/1.16-IAM.json') as jsonIAMUsers:
IAMUsers = json.load(jsonIAMUsers)
usernames = [u['UserName'] for u in IAMUsers['Users']]
功能的默认模式为with
,因此可能会被跳过。