-2

如何将 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 字符串数据存储在字符串数组的每个索引中?

4

1 回答 1

1

将 JSON 解组为 map 的一个问题是它只能深入 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[:]))
}
于 2019-11-11T18:18:22.467 回答