英文:
Getting the map value with Golang
问题
我无法完成这个任务,因为我无法理解逻辑。但是你可以查看我下面的代码示例和输出。我只想在输出中将国家名称作为一个变量返回。
Json文件:https://gist.githubusercontent.com/coderantidote/0894cf7c5204d4c712207ff9162d044d/raw/ab9ec19dcfecd93addb4b1961a2506b34164c090/tld
package main
import (
"fmt"
"strings"
tld "github.com/jpillora/go-tld"
gojsonq "github.com/thedevsaddam/gojsonq/v2"
)
func main() {
urls := []string{
"http://google.com",
"https://eduuk.co.uk/",
"https://www.medi-cal.ca.gov/",
}
for _, url := range urls {
u, _ := tld.Parse(url)
jq := gojsonq.New().File("./tld.json").From("tlds")
tldSlice := strings.Split(u.TLD, ".")
if len(tldSlice) == 2 {
jq.Where("fields.tld", "=", tldSlice[1]).Select("fields.country")
} else {
jq.Where("fields.tld", "strictContains", tldSlice[0]).Select("fields.country")
}
fmt.Printf("%s\n", u.TLD)
fmt.Printf("%v\n", jq.Get())
}
}
输出:
com
[map[country:Commercial organizations]]
co.uk
[map[country:United Kingdom]]
gov
[map[country:US government]]
英文:
I couldn't do it because I didn't fully understand the logic, but you can look at my code example and output below. I just want to return the country name as a variable in the output.
Json File : https://gist.githubusercontent.com/coderantidote/0894cf7c5204d4c712207ff9162d044d/raw/ab9ec19dcfecd93addb4b1961a2506b34164c090/tld
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
package main
import (
"fmt"
"strings"
tld "github.com/jpillora/go-tld"
gojsonq "github.com/thedevsaddam/gojsonq/v2"
)
func main() {
urls := []string{
"http://google.com",
"https://eduuk.co.uk/",
"https://www.medi-cal.ca.gov/",
}
for _, url := range urls {
u, _ := tld.Parse(url)
jq := gojsonq.New().File("./tld.json").From("tlds")
tldSlice := strings.Split(u.TLD, ".")
if len(tldSlice) == 2 {
jq.Where("fields.tld", "=", tldSlice[1]).Select("fields.country")
} else {
jq.Where("fields.tld", "strictContains", tldSlice[0]).Select("fields.country")
}
fmt.Printf("%s\n", u.TLD)
fmt.Printf("%v\n", jq.Get())
}
}
<!-- end snippet -->
Output:
com
[map[country:Commercial organizations]]
co.uk
[map[country:United Kingdom]]
gov
[map[country:US government]]
答案1
得分: 2
这是你要找的吗?
fmt.Printf("%s\n", u.TLD)
fmt.Printf("%v\n", jq.First().(map[string]interface{})["country"])
英文:
Is this what you are looking for?
fmt.Printf("%s\n", u.TLD)
fmt.Printf("%v\n", jq.First().(map[string]interface{})["country"])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论