0

This my json string

var jsonBytes = "\"[{\"Fld1\":10,\"Fld2\":\"0.2\"},{\"Fld1\":10,\"Fld2\":\"0.26
\"}]\""

This string has escaped double quotes. If I Unmarshal it by converting to []bytes, its not working, as the convereted []byte array still has leading and trailing double quotes.

How do I remove those leading and trailing quotes in go?

Fenil Patel
  • 1,528
  • 11
  • 28
user1456110
  • 79
  • 2
  • 12
  • Why don't you simply remove them if you don't need them? `var jsonBytes = "[{\"Fld1\":10,\"Fld2\":\"0.2\"},{\"Fld1\":10,\"Fld2\":\"0.26 \"}]"` – Matthias247 Dec 31 '17 at 05:37
  • 5
    Possible duplicate of [How to unmarshal an escaped JSON string in Go?](https://stackoverflow.com/questions/16846553/how-to-unmarshal-an-escaped-json-string-in-go) – har07 Dec 31 '17 at 05:52
  • What is the code that you run when you "Unmarshal" that string? – Pierre Prinetti Dec 31 '17 at 13:56

1 Answers1

1
  • First mistake is you have enter \n in your jsonBytes. remove that near "0.26
  • you have \ in the first and the last data. I will show you to remove it below :

`

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "reflect"

    "github.com/Gujarats/logger"
)

type Msg struct {
    Channel int    `json:"Fld1"`
    Name    string `json:"Fld2"`
    Msg     string
}

func main() {
    var msg []Msg
    var jsonBytes = "\"[{\"Fld1\":10,\"Fld2\":\"0.2\"},{\"Fld1\":10,\"Fld2\":\"0.26\"}]\""

    // Removing the the first and the last '\'
    newVal := jsonBytes[1 : len(jsonBytes)-1]
    logger.Debug("newval type ", reflect.TypeOf(newVal))
    logger.Debug("newval ", newVal)


    err := json.Unmarshal([]byte(newVal), &msg)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%+v\n", msg)
}
Gujarat Santana
  • 9,854
  • 17
  • 53
  • 75