3

I have a json in the following format

{
    "status_code": 200,
    "status_message": "OK",
    "response": {
        "Messages": [
            "CODE_NOT_AVAILABLE"
        ],
        "UnknownDevices": {
            "": [
                "6",
                "7",
                "8",
                "9",
                "10"
            ]
        }
    }
}

As we see we are missing one index key, after unknownDevices, i am trying to unmarshal this json using golan in the following way

package main

import (
    "encoding/json"
    "fmt"
)

type pushWooshResponse struct {
    Status     int    `json:"status_code"`
    Status_msg string `json:"status_message"`
    Response   response
}

type response struct {
    Message        []string `json:"Messages"`
    UnknownDevices devices
}

type devices struct {
    Udevices []string `json:""`
}

func main() {
    itemInfoR := `{"status_code":200,"status_message":"OK","response":{"Messages":["CODE_NOT_AVAILABLE"],"UnknownDevices":{"devices":["6","7","8","9","10"]}}}`
    itemInfoBytes := []byte(itemInfoR)
    var ItemInfo pushWooshResponse
    er := json.Unmarshal(itemInfoBytes, &ItemInfo)
    if er != nil {
        fmt.Println("Error", er.Error())
    } else {
        fmt.Println(ItemInfo)
    }
}

Output is

{200 OK {[CODE_NOT_AVAILABLE] {[]}}}

Everything is working fine except for the last part, which i am not able to unmarshall this. Can you help me out to umarshal the last part of the json.

12
  • Where is this json coming from? Do you really have no control over it? The empty key is just asking for trouble. I would recommend just making UnknownDevices an array instead of an object. Commented Aug 20, 2015 at 16:12
  • An empty string is a valid key in JSON. Make sure your marshalling method is lossless. Also, in the sample code the empty key is devices instead. Why? Commented Aug 20, 2015 at 16:14
  • In your sample code you have key devices, so you just need to add tag, try this: play.golang.org/p/dACrsAkadN Commented Aug 20, 2015 at 16:16
  • 1
    @RoninDev I am asssuming he is stuck with the empty key in the json. If he can change the json it is easy. Unfortunately, it looks to me like encoding/json can marshall empty keys, but for some reason won't unmarshal them. See play.golang.org/p/ut5D5bR16l EDIT: It won't marshal them either. Commented Aug 20, 2015 at 16:19
  • 1
    Some (now deleted) answers changed the type of the Udevices field. Instead you can implement json.Unmarshaller like so: play.golang.org/p/_TMi53hJ3o (you can also implement a custom marshaller). There may be better solutions. Commented Aug 20, 2015 at 16:19

1 Answer 1

5

There may be other options, but whenever you see strange JSON you can always fall back to implementing your own custom (un)marshalling by implementing json.Unmarshaler and/or json.Marshaler.

Perhaps something like:

type devices struct {
    Udevices []string
}

func (d *devices) UnmarshalJSON(b []byte) error {
    var x map[string][]string
    err := json.Unmarshal(b, &x)
    if err == nil {
        // perhaps check that only a single
        // key exists in the map as well
        d.Udevices = x[""]
    }
    return err
}

func (d devices) MarshalJSON() ([]byte, error) {
    x := map[string][]string{"": d.Udevices}
    return json.Marshal(x)
}

Playground

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

5 Comments

When i am trying something like this play.golang.org/p/Zwc9kQBQN9 it does not work, however, the following works, can what am i missing play.golang.org/p/ut5D5bR16l
You've changed the structure of the JSON so you need to adjust the unmarshalling to handle that. Your question was about unmarshalling "": …
oh ok got it. The reason is I am getting the json as string, so i cannot change it and need to parse it. Sure let me see how i can adjust the unmarshall thanks a lot @Dave
Also sorry i sent the wrong code. play.golang.org/p/zmGeFE8o0V the input looks this way. sorry for the confusion
What if is only an empty array of strings the "json" response I get how to unmarshall something like this [ "some", "som2", "som3" ]

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.