简体   繁体   中英

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)?

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?

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. 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{} . 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[:]))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM