How to convert map[string]interface{} into what the underlying data structure actually is? (JSON-related)

1,629 views
Skip to first unread message

Po Tatoe

unread,
Jan 6, 2015, 12:47:48 AM1/6/15
to golan...@googlegroups.com

Hi,

I have this JSON data...

{
  "bar": {
    "a": "b",
    "x": "y"
  }
}

...which is a map[string]map[string]string

However, json.UnMarshal gives me a map[string]interface {}

How do I convert that back into map[string]map[string]string?

I've tried:

1) .(map[string]map[string]string) but get a panic.

2) Range down into the data structure, but I get: "cannot range over type interface {}".

FYI, my program has no way of knowing the names of the fields/keys in advance, but every key and value is a string and thus will fit into map[string]map[string]string.

Here's my code:

package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"reflect"
)

func main() {
/*
  {
    "bar": {
      "a": "b",
      "x": "y"
    }
  }
*/
fileContents, err := ioutil.ReadFile("./json.txt")
if err != nil {
fmt.Println(err)
os.Exit(1)
}

var f interface{}
err = json.Unmarshal(fileContents, &f)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(f)  // map[bar:map[a:b x:y]]
fmt.Println(reflect.TypeOf(f)) // map[string]interface {}

// now how do I convert f into map[string]map[string]string ?

}


Andrew Bursavich

unread,
Jan 6, 2015, 1:13:47 AM1/6/15
to golan...@googlegroups.com
Just decode it into a value of the correct type from the get go ;)

Andrew Stewart

unread,
Jan 10, 2015, 1:06:10 PM1/10/15
to Andrew Bursavich, golan...@googlegroups.com

This solves my problem and is exactly what I was looking for - thank you very much Andrew!

On Mon, Jan 5, 2015 at 10:13 PM, Andrew Bursavich <aburs...@gmail.com> wrote:
Just decode it into a value of the correct type from the get go ;)

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/S5S93bmRbic/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages