[英]json: cannot unmarshal string into Go value of type map[string]interface {}
[英]Cannot use (type []map[string]interface {}) as type []string in field value
如何將 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)
}
}
在這里我得到了錯誤
cannot use results (type []map[string]interface {}) as type []string in field value
有沒有其他方法可以將每個 json 字符串數據存儲在字符串數組的每個索引中?
將 JSON 解組為 map 的問題之一是它只有一層深:也就是說,如果您嵌套了 Z0ECD11C1D7A287401D148A23BBDhalA2F8Z,則它只會解組您的數據結構的第一層。 這意味着您不僅需要遍歷 map results
,還需要為&StructData{}
構建所需的任何數據類型。 這看起來像這樣:
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.