jojo jojo - 10 months ago 50
JSON Question

array of strings to go struct

This is the command that i execute

$ ps -e
4372 1 4372 4372 ? 197608 03:44:57 /usr/bin/mintty
6476 4372 6476 6208 pty0 197608 03:44:58 /usr/bin/bash
14484 6476 14484 12888 pty0 197608 13:23:48 /usr/bin/ps

I get 1d array of strings using
scanner.scanLines. I need to convert this into array of structs:

type ProcessInfo struct {
PID string `json:"PID"`
PPID string `json:"PPID"`
PGID string `json:"PGID"`
WINPID string `json:"WINPID"`
TTY string `json:"TTY"`
UID string `json:"UID"`
STIME string `json:"STIME"`
COMMAND string `json:"COMMAND"`

Any help would be appreciated.

Answer Source

There is a handy strings.Fields function in strings package that helps to parse this kind of output. Go likes pragmatic approaches, so the naive implementation would be:

  • iterate over your array and split each line into fields with whitespace as separator
  • construct new ProcessInfo object from these fields
  • add this object to the array

Assuming your array is named lines, just do something like this:

var pinfos []ProcessInfo
for _, line := range lines {
    fields := strings.Fields(line)

    pi := ProcessInfo{
        PID:     fields[0],
        PPID:    fields[1],
        PGID:    fields[2],
        WINPID:  fields[3],
        TTY:     fields[4],
        UID:     fields[5],
        STIME:   fields[6],
        COMMAND: fields[7],

    pinfos = append(pinfos, pi)

See the whole code here: