Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang equivalent to Python json.dumps and json.loads

This is a very weird situation but I need to convert a stringified json to something valid that I can unmarshall with:

"{\"hello\": \"hi\"}"

I want to be able to unmarshall this into a struct like this:

type mystruct struct {
    Hello string `json:"hello,string"`
}

I know normally the unmarshall takes bytes but Im trying to convert what I currently get into something structified. Any suggestions?

like image 658
ozn Avatar asked Nov 22 '25 15:11

ozn


1 Answers

The issue is that the encoding/json package accepts well-formed JSON, in this case the initial JSON that you have has escaped quotes, first you have to unescape them, one way to do this is by using the strconv.Unquote function, here's a sample snippet:

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

type mystruct struct {
    Hello string `json:"hello,omitempty"`
}

func main() {
    var rawJSON []byte = []byte(`"{\"hello\": \"hi\"}"`)

    s, _ := strconv.Unquote(string(rawJSON))

    var val mystruct
    if err := json.Unmarshal([]byte(s), &val); err != nil {
        // handle error
    }

    fmt.Println(s)
    fmt.Println(err)
    fmt.Println(val.Hello)
}
like image 176
Tristian Avatar answered Nov 24 '25 08:11

Tristian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!