我一直在研究一种尝试解析嵌套 JSON 响应而不将信息映射到预定义结构的方法。
使用空白界面,它返回为:
map[name:My Folder parentId:1 created:2014-10-09T16:32:07+0000 deleted:false description:Sync Dir id:3 links:[map[rel:self entity:folder href:https://web .domain.org/rest/folders/3 id:3] map[href:https://web.domain.org/rest/folders/1 id:1 rel:parent entity:folder] map[entity:user href: https://web.domain.org/rest/users/1 id:1 rel:creator]] 修改时间:2014-12-18T18:07:01+0000 固定链接:https://web.domain.org/w/ SpJYGQkv syncable:true type:d userId:1]
所以我使用以下内容来浏览这些信息:
func NFind(input interface{}, refs...interface{}) (output interface{}) {
defer func() {if r := recover(); r != nil { output = nil }}()
for _, ref := range refs {
switch cur := ref.(type) {
case string:
output = input.(map[string]interface{})[cur]
case int:
output = input.([]interface{})[cur]
}
}
return output
}
func NMap(input interface{}) (output map[string]interface{}) {
defer func() {if r := recover(); r != nil {}}()
if input == nil { return nil }
return input.(map[string]interface{})
}
func NArray(input interface{}) (output []interface{}) {
defer func() {if r := recover(); r != nil {}}()
if input == nil { return nil }
return input.([]interface{})
}
func NString(input interface{}) (output string) {
defer func() {if r := recover(); r != nil {}}()
if input == nil { return "" }
return input.(string)
}
func NFloat64(input interface{}) (output float64) {
defer func() {if r := recover(); r != nil {}}()
if input == nil { return 0 }
return input.(float64)
}
这是从 JSON 字符串解析信息的可接受方式,还是有更可取的方法?
以下是使用上述内容解析出我当前使用的正确信息的示例:
func mapCache(input map[string]interface{}, valType string) {
fmt.Println(input)
var (
name string
href string
rel string
links []interface{}
myMap map[string]interface{}
)
相关分类