golang json和接口切片
我在迭代包含接口片段的接口片段时遇到问题 这个问题是由于试图使用返回JSON数据的API调用而产生的。返回的数据相当多,根据请求的不同,结构也有很大差异。API文档中也没有JSON响应的结构,因此我尝试实现一些处理任意JSON响应的方法 目前,当进行初始调用时,它被放入map[string]接口{},然后运行switch语句来确定每个元素的类型,当遇到接口片段时,就会出现问题。我似乎对他们无能为力 我尝试过使用sort包几次(特别是sort和slicestable函数),但都没有成功 我收到的错误是:golang json和接口切片,json,go,interface,Json,Go,Interface,我在迭代包含接口片段的接口片段时遇到问题 这个问题是由于试图使用返回JSON数据的API调用而产生的。返回的数据相当多,根据请求的不同,结构也有很大差异。API文档中也没有JSON响应的结构,因此我尝试实现一些处理任意JSON响应的方法 目前,当进行初始调用时,它被放入map[string]接口{},然后运行switch语句来确定每个元素的类型,当遇到接口片段时,就会出现问题。我似乎对他们无能为力 我尝试过使用sort包几次(特别是sort和slicestable函数),但都没有成功 我收到的错
interface conversion: interface {} is []interface {}, not map[string]interface {}
当我尝试映射接口片段以便可以再次使用switch语句对其进行迭代时,就会发生这种情况
output := make(map[string]interface{})
err = json.Unmarshal(body, &output)
fmt.Println(err)
identify(output)
return err
}
func identify(output map[string]interface{}) {
fmt.Printf("%T", output)
for a, b := range output {
switch bb := b.(type) {
case string:
fmt.Println("This is a string")
case float64:
fmt.Println("this is a float")
case []interface{}:
fmt.Println(" is []interface ", bb)
test := b.(map[string]interface{}) // falis here
fmt.Println("Success!", test)
default:
return
}
}
}
因此,基本问题是如何在不事先知道结构的情况下迭代接口的嵌套切片?嗯,您不能将
[]接口{}
强制转换为映射[string]接口{}
。由于它是一个切片,您可以迭代它的元素(请注意,bb
是b
已转换为适当的类型,您不需要再次转换b
):
你为什么要处理一些你不知道的事情?您是否可能重新考虑您的体系结构并使用已知类型?
你看到那张照片了吗?或者尝试一下?您可以添加一个开关案例,用于检查接口片的接口类型,然后运行与递归相同的函数,直到解析整个json
output := make(map[string]interface{})
err = json.Unmarshal(body, &output)
fmt.Println(err)
identify(output)
return err
}
func identify(output map[string]interface{}) {
fmt.Printf("%T", output)
for a, b := range output {
switch bb := b.(type) {
case string:
fmt.Println("This is a string")
case float64:
fmt.Println("this is a float")
case []interface{}:
// Access the values in the JSON object and place them in an Item
for _, itemValue := range jsonObj {
fmt.Printf("%v is an interface\n", itemValue)
identify(itemValue.(map[string]interface{}))
}
default:
return
}
}
}
可以有深度嵌套的json。我们只需要为每种情况创建选项,直到json被完全解析 如果
case[]接口{}:
,则执行test:=b.([]接口{})
,而不是map…
。你知道你可以在一个片上迭代,就像在一个映射上迭代一样,所以不要仅仅为了迭代而尝试键入assert一个片作为一个映射。也许你想要的是bb[0]。(map[string]interface{})
,使用片的元素,而不是再次解析片。
output := make(map[string]interface{})
err = json.Unmarshal(body, &output)
fmt.Println(err)
identify(output)
return err
}
func identify(output map[string]interface{}) {
fmt.Printf("%T", output)
for a, b := range output {
switch bb := b.(type) {
case string:
fmt.Println("This is a string")
case float64:
fmt.Println("this is a float")
case []interface{}:
// Access the values in the JSON object and place them in an Item
for _, itemValue := range jsonObj {
fmt.Printf("%v is an interface\n", itemValue)
identify(itemValue.(map[string]interface{}))
}
default:
return
}
}
}