[英]Cannot use (type []map[string]interface {}) as type []string in field value
How to store Array of JSONs (in string format) in []string (individual JSON string in each index of string array)?如何将 JSON 数组(字符串格式)存储在 []string 中(字符串数组的每个索引中的单个 JSON 字符串)?
package main
import (
"encoding/json"
"fmt"
)
type StructData struct {
Data []string `json:"data"`
}
func main() {
empArray := "[{\"abc\":\"abc\"},{\"def\":\"def\"}]"
var results []map[string]interface{}
json.Unmarshal([]byte(empArray), &results)
pr := &StructData{results}
prAsBytes, err := json.Marshal(pr)
if err != nil {
fmt.Println("error :", err)
}
}
Here I am getting the error在这里我得到了错误
cannot use results (type []map[string]interface {}) as type []string in field value
Is there any other method to store the each json string data in each index of string array?有没有其他方法可以将每个 json 字符串数据存储在字符串数组的每个索引中?
One of the gotchas of unmarshaling JSON to a map is that it only goes 1 level deep: that is, if you have nested JSON, it will only unmarshal the first level of your data structure.将 JSON 解组为 map 的问题之一是它只有一层深:也就是说,如果您嵌套了 Z0ECD11C1D7A287401D148A23BBDhalA2F8Z,则它只会解组您的数据结构的第一层。 This means you'll need to not only iterate through your map
results
but you'll also need to build whatever datatype you need for &StructData{}
.这意味着您不仅需要遍历 map
results
,还需要为&StructData{}
构建所需的任何数据类型。 This would look something like this:这看起来像这样:
package main
import (
"encoding/json"
"fmt"
)
type StructData struct {
Data []string `json:"data"`
}
func main() {
empArray := "[{\"abc\":\"abc\"},{\"def\":\"def\"}]"
var results []map[string]interface{}
json.Unmarshal([]byte(empArray), &results)
// create a new variable that we'll use as the input to StructData{}
var unpacked []string
// iterate through our results map to get the 'next level' of our JSON
for _, i := range results {
// marshal our next level as []byte
stringified, err := json.Marshal(i)
if err != nil {
fmt.Println("error :", err)
}
// add item to our unpacked variable as a string
unpacked = append(unpacked, string(stringified[:]))
}
pr := &StructData{unpacked}
prAsBytes, err := json.Marshal(pr)
if err != nil {
fmt.Println("error :", err)
}
fmt.Println(string(prAsBytes[:]))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.