我想在上面的main
函数中实现这个数组但是怎么做?
hosts := []string{"inanzzz1@100.79.154.22", "inanzzz2@200.79.190.11"}
JSON文件的内容:
inanzzz@inanzzz-VirtualBox:~/go$ go run reader.go < hosts.txt
{
{
"username":"inanzzz1",
"ip":"100.79.154.22"
},
{
"username":"inanzzz2",
"ip":"200.79.190.11"
}
}
GO文件,它读取上面的JSON文件:
package main
import (
"os"
"bufio"
"fmt"
)
func main() {
r := bufio.NewReader(os.Stdin)
line, err := r.ReadString('\n')
for i := 1; err == nil; i++ {
//fmt.Printf("Line %d: %s", i, line)
fmt.Printf(line)
line, err = r.ReadString('\n')
}
}
答案 0 :(得分:2)
假设你拥有的是一个json数组(第一个和最后一个{}被[]替换)而不是hosts.txt中描述的无效JSON,你有一个可行的解决方案:
package main
import (
"encoding/json"
"fmt"
"os"
)
type UsernameIp struct {
Username string `json:"username"`
Ip string `json:"ip"`
}
func main() {
j := json.NewDecoder(os.Stdin)
var src []UsernameIp
j.Decode(&src)
var hosts []string
for _, h := range src {
entry := fmt.Sprintf("%s@%s", h.Username, h.Ip)
hosts = append(hosts, entry)
}
fmt.Println(hosts)
}
更正hosts.txt文件:
[
{
"username":"inanzzz1",
"ip":"100.79.154.22"
},
{
"username":"inanzzz2",
"ip":"200.79.190.11"
}
]
答案 1 :(得分:1)
你可能应该首先解组json然后迭代结果。
首先 - 使hosts.txt成为有效的JSON。对于该用途[]
而不是{}
:
[
{
"username":"inanzzz1",
"ip":"100.79.154.22"
},
{
"username":"inanzzz2",
"ip":"200.79.190.11"
}
]
然后解散。
以下是完整示例:
package main
导入( “FMT” “编码/ JSON”
)func main(){
type host struct { Username string Ip string } cont := ` [ { "username":"inanzzz1", "ip":"100.79.154.22" }, { "username":"inanzzz2", "ip":"200.79.190.11" } ] ` // Read file to some byte array. We will use string for this example. var arr []host err := json.Unmarshal([]byte(cont), &arr) if err != nil { fmt.Println(err) } hosts := make([]string, len(arr)) for i, h := range arr { hosts[i] = h.Username + "@" + h.Ip } fmt.Println(hosts)
}
答案 2 :(得分:0)
您可以使用ioutil.ReadFile将整个文件作为一个字符串读取,该字符串是一个json文档,然后将该字符串解组为一个结构,您可以使用它来方便访问:
type user_ip struct{
username string `json:"username"`
ip string `json:"ip"`
}
type jsonStruct struct{
sample []user_ip
}
func main() {
//you'll have to read file here
str := `{
{
"username":"inanzzz1",
"ip":"100.79.154.22"
},
{
"username":"inanzzz2",
"ip":"200.79.190.11"
}
}`
userIP := jsonStruct{}
err := json.Unmarshal(str, &userIP)
panic(err)
//do what you want with the struct here
}