-2

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?

  • 1
    `StructData.Data` is a field of type `[]string`. How could you set (assign) a map (`results`) to it? – icza Nov 11 '19 at 11:35
  • https://golang.org/doc/faq#convert_slice_of_interface – Volker Nov 11 '19 at 11:37
  • I want to store individual json string in each index of string array. My approach may be wrong by assigning []map[string]interface {} to [] string! Is there any method to do? –  Nov 11 '19 at 11:38
  • Maybe you want `Data []json.RawMessage`? – Jonathan Hall Nov 11 '19 at 11:44
  • So, how to convert empArray to that format? –  Nov 11 '19 at 11:57
  • @VenkateshS Is this what you looking for https://play.golang.com/p/SSEsADYyqOC? Or do you want the individual json *objects* to be turned into json strings? – mkopriva Nov 11 '19 at 15:14

1 Answers1

2

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