json.number in struct

172 views
Skip to first unread message

irvan hendrik

unread,
Nov 1, 2020, 7:28:07 PM11/1/20
to golang-nuts
Hi, I have 
type Product struct {
Weight json.Number 
}

func (p Product) GetWeight() float64 {
tmp, _ := p.Weight.Float64()
return tmp
}

I would like to be able to call and assign the variable directly. I got the GetWeight() to help me convert from json.Number to float64.
How to assign the variable? 
I would like to be able to use
p Product
&p.Weight
 
Can some one help me or simplify the GetWeight also maybe?
because right now I can only do it by:
var tempWeight float32
assign using &tempWeight
then 
p.Product = json.Number(fmt.Sprintf("%f", tempWeight))

Thank you.


Brian Candler

unread,
Nov 2, 2020, 2:46:28 AM11/2/20
to golang-nuts
Is there a particular reason why you don't just do this?

type Product struct {
    Weight float64
}

That should serialize to/from JSON just fine.  You can also include metadata about how you want it serialized:

type Product struct {
    Weight float64 `json:"weight,omitempty"`
}


irvan hendrik

unread,
Nov 2, 2020, 6:30:43 AM11/2/20
to Brian Candler, golang-nuts
yes. because when I marshal it to json the number got messed up.
when I entered value 10.0 it became 10.
If I use json.number it keeps the format 10.0.

Regards.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/07b5217b-2b7e-47e0-8316-fba13d869cado%40googlegroups.com.

Jan Mercl

unread,
Nov 2, 2020, 6:36:07 AM11/2/20
to irvan hendrik, Brian Candler, golang-nuts
On Mon, Nov 2, 2020 at 12:30 PM irvan hendrik <irvan....@gmail.com> wrote:

> yes. because when I marshal it to json the number got messed up.
> when I entered value 10.0 it became 10.
> If I use json.number it keeps the format 10.0.

Sounds like conflating data and their representation. I'm not a json
expert, but AFAIK, the sequence of characters `10` and `10.0`
represent the very same json number.

Urjit Singh Bhatia

unread,
Nov 4, 2020, 2:55:17 PM11/4/20
to golang-nuts
Yeah, iirc JSON doesn't really have a clear distinction between float and int because it has to sort of stay parallel to javascript.

Found this link that explains a bit more...
Excerpt:
```The precise treatment of the “integer” type may depend on the implementation of your JSON Schema validator. JavaScript (and thus also JSON) does not have distinct types for integers and floating-point values. Therefore, JSON Schema can not use type alone to distinguish between integers and non-integers. ```
from https://json-schema.org/understanding-json-schema/reference/numeric.html#id4
Reply all
Reply to author
Forward
0 new messages