无法将(类型[] map [string] interface {})用作字段值中的类型[] string

如何在[] string(字符串数组的每个索引中的单个JSON字符串)中存储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字符串数据存储在字符串数组的每个索引中吗?

liuqinjian 回答:无法将(类型[] map [string] interface {})用作字段值中的类型[] string

将JSON编组到地图的要点之一是,它仅深入1层:也就是说,如果您嵌套了JSON,它将仅解组数据结构的第一层。这意味着您不仅需要遍历地图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[:]))
}
本文链接:https://www.f2er.com/3124571.html

大家都在问