6

I have the following types:

type IPFilePair struct {
    IP net.IP
    FileName string
}

type IPFilePairs []*IPFilePair

I'm trying to marshal the JSON of this using json.Marshal(sample_ipfilepairs) but because IP isn't a string, it changes it into something strange.

What is the proper way to make the JSON of this output IP as a string?

1 Answer 1

10

I think if you have access to the definition of IPFilePair, creating local typedef of net.IP that you add MarshanJSON() to is the way to go:

package main

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

type netIP net.IP

type IPFilePair struct {
    IP netIP
    FileName string
}

type IPFilePairs []*IPFilePair

func (ip netIP) MarshalJSON() ([]byte, error) {
    return json.Marshal(net.IP(ip).String())
}

func main() {
    pair1 := IPFilePair{netIP{127, 0, 0, 1}, "file1"}
    pair2 := IPFilePair{netIP{127, 0, 0, 2}, "file2"}
    sample_ipfilepairs := IPFilePairs{&pair1, &pair2}

    b, _ := json.Marshal(sample_ipfilepairs)
    fmt.Println(string(b))
}

This outputs:

[{"IP":"127.0.0.1","FileName":"file1"},{"IP":"127.0.0.2","FileName":"file2"}]

Of course, if you ever need to unmarshal that back into the same Go data structure, you'll want to implement UnmarshalJSON() on netIP using net.ParseIP.

I'm certainly curious if anyone knows of an easier way to accomplish this.

Sign up to request clarification or add additional context in comments.

3 Comments

It's a shame you can't just add the MarshalJSON method directly to net.IP, but I guess that is one of the restrictions needed to be able to compile modules separate from the full program.
@JamesHenstridge. Agreed. This is the best way I know how to do it, but I was kind of hoping someone more fluent in Go than I am would come along and show a simpler solution.
One alternative would be to implement your MarshalJSON method at the IPFilePairs level. You could build a map[string] interface{} holding the stringified IP address and filename and marshal that. That lets you use net.IP directly, but adds work everywhere you want to embed an IP address.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.