0

Is there a way in golang to decode any json value to a string. Similar to json.Number why isn't there a json.String?

For example, the following could be decoded as indicated

{"number": 123}      => "123"
{"string": "123"}    => "123"
{"float" : 123.45}   => "123.45"
{"bool"  : true}     => "true"
{"empty" : ""}       => ""
{"null"  : null}     => ""
4
  • Not entirely sure what you mean because json.Number is a type (basically just a string) which stands for a numeral literal inside the loaded JSON structure, used because you can't map the JSON number type 1:1. As I understand, it's not a conversion function the way you think. You just need to access the field you want and convert it to a string if you want a string... Commented Jul 12, 2016 at 11:29
  • (JSON string fields don't need their own special type, they are just stored as Go string in the structure.) Commented Jul 12, 2016 at 11:31
  • Plus, the json.Number type is only used if you use Decoder.UseNumber(), I think. Otherwise it is just stored as float64 and the problem is that huge numbers can't properly stored this way (that's why the json.Number type exists). See attilaolah.eu/2013/11/29/json-decoding-in-go/… Commented Jul 12, 2016 at 11:32
  • @CherryDT A use case for me would be where I want to read a url query param from json. I don't care what the type of the json value is, it must always be decoded as a string Commented Jul 12, 2016 at 11:46

1 Answer 1

4

Inspired by this post I created a JsonString type. It will decode any string, number, boolean or null values to a string.

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

type JsonString string
type jsonString JsonString
func (st *JsonString) UnmarshalJSON(bArr []byte) (err error) {
    j, n, f, b := jsonString(""), uint64(0), float64(0), bool(false)
    if err = json.Unmarshal(bArr, &j); err == nil {
        *st = JsonString(j)
        return
    }
    if err = json.Unmarshal(bArr, &n); err == nil {
        *st = JsonString(string(bArr[:]))
        return
    }
    if err = json.Unmarshal(bArr, &f); err == nil {
        *st = JsonString(string(bArr[:]))
        return
    }
    if err = json.Unmarshal(bArr, &b); err == nil {
        *st = JsonString(string(bArr[:]))
        return
    }
    return
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.