Home > Software design >  Converting an slice of strings that represent JSON to JSON and responding to a request
Converting an slice of strings that represent JSON to JSON and responding to a request

Time:10-09

I have a slice of strings ([]string) and would like to convert it to JSON.

Here is what my slice looks like when I fmt.Println()

[
    {\"field1\": \"data1\",  \"field2\": \"data2\"},
    {\"secondField1\": \"data1\",  \"secondfield2\": \"data2\"}
]

EDIT

I want to send it as a response to a HTTP request.

Here is my code.

jsonString := `"{"field1": "data1",  "field2": "data2"}",
               "{"secondField1": "data1",  "secondfield2": "data2"}"`

json.NewEncoder(w).Encode(jsonString)

w is a http.ResponseWriter


ANSWER

mkopriva has commented on the original question and his solution worked.

Here is the link he provided.

https://play.golang.org/p/n5b5ec4297K

Here is the code that worked for me (you can find it in the playground link)

    jsonArray := make([]json.RawMessage, len(stringSlice))

    for i := range stringSlice {
        jsonArray[i] = json.RawMessage(stringSlice[i])
    }

    if err := json.NewEncoder(os.Stdout).Encode(jsonArray); err != nil {
        panic(err)
    }

CodePudding user response:

From your question I understand that you want to write the json on a http.ResponseWriter. In that case I would suggest an approach like this:

func handle(w http.ResponseWriter, r *http.Request) {
   myslice := []string{"", "", ""}
   data, err := json.Marshal(myslice)
   if err != nil {
       log.Println("could not marshal", err)
       return
   }
   w.Write(data)
}

Please note that the error handling is not so nice here, and perhaps you would need to add something about content-type to the header, but that is beyond this example.

CodePudding user response:

ANSWER

mkopriva has commented on the original question and his solution worked.

Here is the link he provided.

https://play.golang.org/p/n5b5ec4297K

Here is the code that worked for me (you can find it in the playground link)

    jsonArray := make([]json.RawMessage, len(stringSlice))

    for i := range stringSlice {
        jsonArray[i] = json.RawMessage(stringSlice[i])
    }

    if err := json.NewEncoder(os.Stdout).Encode(jsonArray); err != nil {
        panic(err)
    }
  • Related