I have a little question for you all!
How foreach each element in json file?
json:
{
"keywords": "keywords1",
"social": [
{"url": "test1", "title": "test1"},
{"url": "test2", "title": "test2"}
]
}
and this:
package main
import (
"fmt"
"encoding/json"
"io/ioutil"
)
func main() {
configFile, _ := ioutil.ReadFile("config.json")
json.Unmarshal(configFile, &person)
// foreach["social"]
}
If you are using a map, you can use key, value := range mymap. Example:
package main
import (
"fmt"
"encoding/json"
"io/ioutil"
)
func main() {
configFile, _ := ioutil.ReadFile("config.json")
json.Unmarshal(configFile, &person)
for key, value := range person{}
}
Method #1: query map[string]interface{}
(play):
package main
import (
"encoding/json"
"fmt"
)
func main() {
person := make(map[string]interface{})
json.Unmarshal([]byte(`{
"keywords": "keywords1",
"social": [
{"url": "test1", "title": "test1"},
{"url": "test2", "title": "test2"}
]
}`), &person)
social, _ := person["social"]
fmt.Println(social)
}
Prints:
[map[url:test1 title:test1] map[url:test2 title:test2]]
Method #2: nice intermediate object (play):
package main
import (
"encoding/json"
"fmt"
)
func main() {
var person struct {
Keywords string `json:"keywords"`
Social []struct {
Url string `json:"url"`
Title string `json:"title"`
} `json:"social"`
}
json.Unmarshal([]byte(`{
"keywords": "keywords1",
"social": [
{"url": "test1", "title": "test1"},
{"url": "test2", "title": "test2"}
]
}`), &person)
for _, i := range person.Social {
fmt.Println(i.Url, i.Title)
}
}
Prints:
test1 test1
test2 test2