Jorge Olivero
Jorge Olivero

Reputation: 3863

Golang Converting JSON

map[key:2073933158088]

I need to grab the key out of this data structure as a string, but I can't seem to figure out how!

Help with this overly simple question very much appreciated.

The value above is encapsulated in the variable named data.

I have tried: data.key, data[key], data["key"], data[0] and none of these seem to be appropriate calls.

To define data I sent up a JSON packet to a queue on IronMQ. I then pulled the message from the queue and manipulated it like this:

payloadIndex := 0

for index, arg := range(os.Args) {
        if arg == "-payload" {
                payloadIndex = index + 1
        }
}

if payloadIndex >= len(os.Args) {
        panic("No payload value.")
}

payload := os.Args[payloadIndex]

var data interface{}

raw, err := ioutil.ReadFile(payload)

if err != nil {
    panic(err.Error())
}

err = json.Unmarshal(raw, &data)

Upvotes: 2

Views: 1074

Answers (2)

fsouza
fsouza

Reputation: 41

Since the number in the json is unquoted, it's not a string, Go will panic if you try to just handle it as a string (playground: http://play.golang.org/p/i-NUwchJc1).

Here's a working alternative:

package main

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

type Data struct {
    Key string `json:"key"`
}

func (d *Data) UnmarshalJSON(content []byte) error {
    var m map[string]interface{}
    err := json.Unmarshal(content, &m)
    if err != nil {
        return err
    }
    d.Key = strconv.FormatFloat(m["key"].(float64), 'f', -1, 64)
    return nil
}

func main() {
    data := new(Data)
    text := `{"key":2073933158088}`
    raw := []byte(text)
    err := json.Unmarshal(raw, data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Println(data.Key)
}

You can see the result in the playground: http://play.golang.org/p/5hU3hdV3kK

Upvotes: 2

Grzegorz Żur
Grzegorz Żur

Reputation: 49241

Design your data type to match json structure. This is how can you achieve this:

package main

import (
    "fmt"
    "encoding/json"
)

type Data struct {
    Key string `json:"key"`
}

func main() {
    data := new(Data)
    text := `{ "key": "2073933158088" }`
    raw := []byte(text)
    err := json.Unmarshal(raw, data)
    if err != nil {
        panic(err.Error())  
    }
    fmt.Println(data.Key)
}

Upvotes: 2

Related Questions