GO language: Reading a file and turning the content into an array -
i want implement array in main
function above how?
hosts := []string{"inanzzz1@100.79.154.22", "inanzzz2@200.79.190.11"}
content of json file:
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 file reads json file above:
package main import ( "os" "bufio" "fmt" ) func main() { r := bufio.newreader(os.stdin) line, err := r.readstring('\n') := 1; err == nil; i++ { //fmt.printf("line %d: %s", i, line) fmt.printf(line) line, err = r.readstring('\n') } }
assuming have json array (first , lastly {} replaced []) instead of invalid json described in hosts.txt here have working solution:
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 _, h := range src { entry := fmt.sprintf("%s@%s", h.username, h.ip) hosts = append(hosts, entry) } fmt.println(hosts) }
correct hosts.txt file:
[ { "username":"inanzzz1", "ip":"100.79.154.22" }, { "username":"inanzzz2", "ip":"200.79.190.11" } ]
go
No comments:
Post a Comment