GO language: Reading a file and turning the content into an array

huangapple go评论96阅读模式
英文:

GO language: Reading a file and turning the content into an array

问题

我想在上面的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"
   }
}

读取上述JSON文件的GO文件:

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')
    }
}
英文:

I want to implement this array in main function above but how?

hosts := []string{&quot;inanzzz1@100.79.154.22&quot;, &quot;inanzzz2@200.79.190.11&quot;}

Content of JSON file:

inanzzz@inanzzz-VirtualBox:~/go$ go run reader.go &lt; hosts.txt 
{
   {
      &quot;username&quot;:&quot;inanzzz1&quot;,
      &quot;ip&quot;:&quot;100.79.154.22&quot;
   },
   {
      &quot;username&quot;:&quot;inanzzz2&quot;,
      &quot;ip&quot;:&quot;200.79.190.11&quot;
   }
}

GO file which reads the JSON file above:

package main

import (
    &quot;os&quot;
    &quot;bufio&quot;
    &quot;fmt&quot;
)

func main() {
    r := bufio.NewReader(os.Stdin)
    line, err := r.ReadString(&#39;\n&#39;)
    for i := 1; err == nil; i++ {
        //fmt.Printf(&quot;Line %d: %s&quot;, i, line)
        fmt.Printf(line)
        line, err = r.ReadString(&#39;\n&#39;)
    }
}

答案1

得分: 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"
   }
]

请注意,这只是一个代码示例,用于将 JSON 数据解析为 Go 结构体,并将结果打印出来。你可以根据自己的需求进行修改和扩展。

英文:

Assuming that what you have is a json array (first and last {} replaced by []) instead of the invalid JSON described in hosts.txt here you have a working solution:

package main

import (
	&quot;encoding/json&quot;
	&quot;fmt&quot;
	&quot;os&quot;
)

type UsernameIp struct {
	Username string `json:&quot;username&quot;`
	Ip       string `json:&quot;ip&quot;`
}

func main() {
	j := json.NewDecoder(os.Stdin)
	var src []UsernameIp
	j.Decode(&amp;src)

	var hosts []string
	for _, h := range src {
		entry := fmt.Sprintf(&quot;%s@%s&quot;, h.Username, h.Ip)
		hosts = append(hosts, entry)
	}

	fmt.Println(hosts)
}

Correct hosts.txt file:

[
   {
      &quot;username&quot;:&quot;inanzzz1&quot;,
      &quot;ip&quot;:&quot;100.79.154.22&quot;
   },
   {
      &quot;username&quot;:&quot;inanzzz2&quot;,
      &quot;ip&quot;:&quot;200.79.190.11&quot;
   }
]

答案2

得分: 1

你应该先解析JSON,然后再迭代结果。
首先,将hosts.txt转换为有效的JSON格式。使用[]代替{}

[
   {
      "username":"inanzzz1",
      "ip":"100.79.154.22"
   },
   {
      "username":"inanzzz2",
      "ip":"200.79.190.11"
   }
]

然后进行解析。

以下是完整示例代码:

package main

import (
	"fmt"
	"encoding/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"
   }
]`

	// 将文件读取到字节数组中。这个示例中我们使用字符串。
	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)
}

希望对你有帮助!

英文:

You probably should unmarshall json first and then iterate over result.
First - make hosts.txt a valid JSON. For that use [] instead of {}:

[
   {
      &quot;username&quot;:&quot;inanzzz1&quot;,
      &quot;ip&quot;:&quot;100.79.154.22&quot;
   },
   {
      &quot;username&quot;:&quot;inanzzz2&quot;,
      &quot;ip&quot;:&quot;200.79.190.11&quot;
   }
]

Then unmarshall.

Here is full example:

> package main
>
> import (
> "fmt"
> "encoding/json"
> )
>
> func main() {
>
> type host struct {
> Username string
> Ip string
> }
>
> cont := [
&gt; {
&gt; &quot;username&quot;:&quot;inanzzz1&quot;,
&gt; &quot;ip&quot;:&quot;100.79.154.22&quot;
&gt; },
&gt; {
&gt; &quot;username&quot;:&quot;inanzzz2&quot;,
&gt; &quot;ip&quot;:&quot;200.79.190.11&quot;
&gt; }
&gt; ]
&gt;

>
>
> // 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)
> }

答案3

得分: 0

你可以使用ioutil.ReadFile将整个文件读取为一个字符串,该字符串是一个JSON文档,然后将该字符串解析为一个你事先定义好的结构体,以便于访问:

type user_ip struct{
    username string `json:"username"`
    ip string       `json:"ip"`
}

type jsonStruct struct{
    sample []user_ip
}


func main() {

    //在这里你需要读取文件
    str := `{
               {
                  "username":"inanzzz1",
                  "ip":"100.79.154.22"
               },
               {
                  "username":"inanzzz2",
                  "ip":"200.79.190.11"
               }
            }`

    userIP := jsonStruct{}

    err := json.Unmarshal([]byte(str), &userIP)
    panic(err)

    //在这里对结构体进行操作
}
英文:

You can use ioutil.ReadFile to read the whole file as a string which is a json document and then Unmarshal the string into a struct that you will have made for easy access:

type user_ip struct{
	username string `json:&quot;username&quot;`
	ip string       `json:&quot;ip&quot;`
}

type jsonStruct struct{
	sample []user_ip
}


func main() {

	//you&#39;ll have to read file here
    str := `{
			   {
			      &quot;username&quot;:&quot;inanzzz1&quot;,
			      &quot;ip&quot;:&quot;100.79.154.22&quot;
			   },
			   {
			      &quot;username&quot;:&quot;inanzzz2&quot;,
			      &quot;ip&quot;:&quot;200.79.190.11&quot;
			   }
			}`

	userIP := jsonStruct{}

	err := json.Unmarshal(str, &amp;userIP)
	panic(err)

	//do what you want with the struct here
}

huangapple
  • 本文由 发表于 2014年11月14日 03:55:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/26917262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定