1

This is the struct I have:

type Resource struct {
    Name string `json:"name"`
    Ranges struct {
        Range []struct {
            Begin int `json:"begin"`
            End   int `json:"end"`
        } `json:"range"`
    } `json:"ranges,omitempty"`
    Role string `json:"role,omitempty"`
    Type string `json:"type"`
    Scalar Scalar `json:"scalar,omitempty"`
}

I don't know how to make fields in the JSON not null. For example, struct Range like that:

{
    "name": "cpus",
    "ranges": {
        "range": null
    },
    "type": "SCALAR",
    "scalar": {
        "value": 1
    }
}, {
    "name": "mem",
    "ranges": {
        "range": null
}
Omar Einea
  • 2,420
  • 6
  • 22
  • 35
iFreezy
  • 11
  • 2
  • Please create [Minimal, Complete, and Verifiable](https://stackoverflow.com/help/mcve) example. Post the json that you want to unmarshal – Himanshu Mar 03 '18 at 18:27
  • https://stackoverflow.com/a/31048860/1135424 – nbari Mar 03 '18 at 18:31
  • 1
    Either allocate the value of the `Range` field so that it isn't `nil`, or add `,omitempty` to the json tag so that the json property is omitted if the `Range` field is `nil`. See here: https://play.golang.org/p/GWWm5yAP7lU – mkopriva Mar 03 '18 at 18:40
  • 1
    You can also define a type that will implement the `json.Marshaler` interface and have it decide how it's gonna be marshaled if it's empty or nil. https://play.golang.org/p/UJK5cjkctIw – mkopriva Mar 03 '18 at 21:06

3 Answers3

0

a way to do that is assign range as *string and then you should compare it with nil or not, if not nil convert it to string and marshall it again

CallMeLoki
  • 1,292
  • 10
  • 21
0

assuming that you want to marshal the structs in your question and get a json output that looks like this:

  {
    "name": "cpus",
    "ranges": {
      "range": []
    },
    "type": "SCALAR",
    "scalar": {
      "value": 1
    }
  },
  {
    "name": "mem",
    "ranges": {
      "range": []
    }
  }

In golang slices [] are a reference type, that are backed by an array. You can read up on the internals of slices here: https://blog.golang.org/go-slices-usage-and-internals

Basically the reason that you are getting null in the output is because you have not instantiated the slice, the slice is essentially a pointer, and that pointer is nil.

Create a new empty slice, like []Range{} and assign that to the field in Resource that is currently null in the json, and instead of a nil pointer, you will have an empty slice that will be marshalled as [] and not null.

Zak
  • 4,867
  • 15
  • 28
0

That changes struct is resolved my problem:

type Resource struct {
    Name   string  `json:"name"`
    Ranges *Ranges  `json:"ranges,omitempty"`
    Role   string  `json:"role,omitempty"`
    Type   string  `json:"type"`
    Scalar *Scalar `json:"scalar,omitempty"`
}
iFreezy
  • 11
  • 2