Created
October 25, 2017 01:53
-
-
Save cuixin/f10cea0f8639454acdfbc0c9cdced764 to your computer and use it in GitHub Desktop.
json to map[string]interface{} example in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
func dumpMap(space string, m map[string]interface{}) { | |
for k, v := range m { | |
if mv, ok := v.(map[string]interface{}); ok { | |
fmt.Printf("{ \"%v\": \n", k) | |
dumpMap(space+"\t", mv) | |
fmt.Printf("}\n") | |
} else { | |
fmt.Printf("%v %v : %v\n", space, k, v) | |
} | |
} | |
} | |
var jsonStr = ` | |
{ | |
"array": [ | |
1, | |
2, | |
3 | |
], | |
"boolean": true, | |
"null": null, | |
"number": 123, | |
"object": { | |
"a": "b", | |
"c": "d", | |
"e": "f" | |
}, | |
"string": "Hello World" | |
} | |
` | |
func main() { | |
jsonMap := make(map[string]interface{}) | |
err := json.Unmarshal([]byte(jsonStr), &jsonMap) | |
if err != nil { | |
panic(err) | |
} | |
dumpMap("", jsonMap) | |
} |
If I want to load a variable from outside into jsonStr, how do I do it?
Look at fmt.Sprintf to format provided values into the string. https://pkg.go.dev/fmt#Sprintf
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If I want to load a variable from outside into jsonStr, how do I do it?