【发布时间】:2018-04-17 20:02:19
【问题描述】:
我有一个 json 文件(嵌套 json),我正在将其内容解组到一个 map[string] 接口中。现在我必须实现分页,因为数据很大。客户端将作为查询参数发送所需的页面,我如何分割我拥有的数据? 这是我正在处理的数据的 sn-p:
"packages":{
"pkg1": {
"meta": {
"description": "description1",
"name": "pkg1.1"
},
"name": "pkg1.1"
},
"pkg2": {
"meta": {
"description": "description2",
"name": "pkg2.2"
},
"name": "pkg2.2"
},
}
所以我所做的是我递归地遍历数据并创建了一个自定义类型的 array,其中包含我需要为每个条目(名称、描述)的数据,以便我可以将它用于分页。这是我使用的代码:
type Object struct {
name string
description string
}
func iterate(aMap map[string]interface{}, result *[]Object){
for key, val := range aMap {
switch val.(type) {
case map[string]interface{}:
if(key == "meta"){
switch reflect.TypeOf(val).Kind() {
case reflect.Map:
s := reflect.ValueOf(val)
var tmpData Object
if(s.MapIndex(reflect.ValueOf("name")).IsValid()){
tmpData.name = s.MapIndex(reflect.ValueOf("name")).Interface().(string)
}
if(s.MapIndex(reflect.ValueOf("description")).IsValid()){
tmpData.description = s.MapIndex(reflect.ValueOf("description")).Interface().(string)
}
*result = append(*result, tmpData)
}
}
iterate(val.(map[string]interface{}), result)
default: //DO NOTHING!!
}
}
}
【问题讨论】:
-
你试过什么?尝试一些东西,然后在遇到错误时返回。
-
您想在解组之前对数据进行切片,还是对解组后的结果进行切片?
-
对未编组的结果进行切片
标签: go pagination