I need to find a way to convert a table to JSON with golang
The table in question looks like:
State Version Support eRSTP Enhancements Bridge Priority Hello Time Max Age Time Transmit Count Forward Delay Max Hops Cost Style BPDU Guard Timeout VersionForSNMP
Disabled RSTP On 0 2 s 20 s 32 15 s 20 STP (16 bit) Don't shutdown RSTP
Splitting the columns is simple, a split is enough. But notice that there is no pattern of separation in the values, sometimes it is a space, sometimes a tab and sometimes the field is empty
Would there be any way to "parse" this table so that each value goes to its appropriate field?
I hope something like this
[{"State": "Disabled",
"Version": "RSTP",
…
}]
2
Answers
The first issue is that it’s not sure what the column headers even are? Going by the example, it could be
State
: Disabled,Version Support
: RSTP (orVersion
: RSTP andSupport
: [empty]?),eRSTP Enhancements
: On (oreRSTP
: On andEnhancements
: [empty]?),Bridge Priority
: 0,Hello Time
: 2 s,Max Age Time
: 20 s,Transmit Count
: 32,Forward Delay
: 15 s,Max Hops
: 20 etc. First of all, you should clarify that.Other than that, I can’t give you a definite answer, only some ideas:
State
is always a string (maybe with a limited set of values?),Version
(orVersion Support
?) the same,eRSTP
(oreRSTP Enhancements
?) is maybe just "On" or "Off",Bridge Priority
is always numeric,Hello Time
is numeric followed by "s" etc. This way you can maybe identify which column the field belongs to even if some fields are empty.This is an interesting problem, and I think it can be solved with the following algorithm, actually:
headers[i - 1] == " " && headers[i] != " " && data[i - 1] == " " && data [i] != " "
Once we found those indexes, we can use them to extract the substrings.
This is basically a sliding window of size 2×2.
In first iteration:
In the second iteration:
And so on.
Now, let’s implement this in Go:
What we have now are all the indexes that satisfy our requirements.
What’s left is just to parse each row using those indexes.
Now, it’s not clear if you expect to always have just two rows as your input or not. But I believe that converting from
[][]string
to the JSON output of your liking should be rather easy.