Jeffail/gabs

Create JSON from CSV

Closed this issue · 2 comments

the42 commented

I have a CSV like

id,name,size
external,Facebook,25
external.internal,MyApp,17

and I would like to create a JSON dynamically like
{
"id":"external",
"children": [{"name": "Facebook"}, {"size":25},
{"id": "internal,
"children": [{"name":"MyApp"}, {"size":17}]
}
]
}

I though this should be trivial with gabs. I already collect the CSV headers. What I have so far is

{
				if idx == 0 {
					jc, _ = jc.ObjectP(str)
					// The first element defines the hierarchy
					jc, err = jc.SetP(str, "id")
					if idx := strings.LastIndex(str, "."); idx > 0 {
						path = str[0 : idx+1]
					}
					path += "children"
				} else {
					if jc, err = jc.ArrayP(path); err != nil {
						log.Fatalf("ArrayP: at index %d, path %s, value: %s - %s", idx, path, str, err.Error())
					}

					if jc = jc.ArrayAppendP(str, path+"."+heading[idx]); err != nil {
						log.Fatalf("SetP: at index %d, path %s, value: %s - %s", idx, path, str, err.Error())
					}
				}
			}

But all it creates when calling jc.StringIdent is a single element (when there are no values besides id in the CSV or it fails telling me that there is a collision.

the42 commented

If this question is to big, I think I can solve my problems if I can manage to create a JSON with gabs which looks like:

{
  "values": [{"name":"Jack"},{"size":12}]
}

so objects, where I can set key / value dynamically, inside an array . I have no structs to serialize but read it as key/value from a Csv.

the42 commented

Closing for being to unspecific