0

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

hosts := []string{"[email protected]", "[email protected]"}

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 which reads the JSON file above:

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

3 Answers 3

2

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 (
    "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)
}

Correct hosts.txt file:

[
   {
      "username":"inanzzz1",
      "ip":"100.79.154.22"
   },
   {
      "username":"inanzzz2",
      "ip":"200.79.190.11"
   }
]
Sign up to request clarification or add additional context in comments.

2 Comments

When I run it with go run json.go < hosts.txt I get [] as result
You need to have a valid JSON file. If you pass the file you suggested as an example in through a linter you will see it is not valid. A JSON array starts and ends with []
1

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

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

Then unmarshall.

Here is full example:

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"
   }
]
 `


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

}

1 Comment

I'm trying to remove your hard coded JSON variable and implement "reading a txt file" feature instead. So how should I modify your code. I'm running it with go run json.go < hosts.txt
0

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:"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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.