我有一个小问题!
如何在json文件中预处理每个元素?
JSON:
{
"keywords": "keywords1",
"social": [
{"url": "test1", "title": "test1"},
{"url": "test2", "title": "test2"}
]
}
和此:
package main
import (
"fmt"
"encoding/json"
"io/ioutil"
)
func main() {
configFile, _ := ioutil.ReadFile("config.json")
json.Unmarshal(configFile, &person)
// foreach["social"]
}
答案 0 :(得分:0)
如果您使用的是地图,则可以使用key,value:= range mymap。例如:
package main
import (
"fmt"
"encoding/json"
"io/ioutil"
)
func main() {
configFile, _ := ioutil.ReadFile("config.json")
json.Unmarshal(configFile, &person)
for key, value := range person{}
}
答案 1 :(得分:-1)
方法#1:查询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)
}
打印:
[map[url:test1 title:test1] map[url:test2 title:test2]]
方法#2:漂亮的中间对象(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)
}
}
打印:
test1 test1
test2 test2