You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Create a new gabs container
container := gabs.New()
// Iterate through the flattened data and set values in the container
for path, value := range flattenedData {
container.SetP(value, path)
}
// Print the nested JSON as a string
fmt.Println(container.StringIndent("", " "))
Hey @WTIGER001 👋 Guess you can get away with something like this:
package main
import (
"fmt""slices""strconv""github.com/Jeffail/gabs/v2"
)
funcmain() {
flattenedData:=map[string]interface{}{
"foo.arr.0": "apple",
"foo.arr.1": "banana",
"oarr.0.id": "id1",
"oarr.1.id": "id2",
"foo.bar": "foobar",
}
// Create a new gabs containercontainer:=gabs.New()
// Iterate through the flattened data and set values in the containerforpath, value:=rangeflattenedData {
segments:=gabs.DotPathToSlice(path)
isArray:=falseforloc, segment:=rangesegments {
if_, err:=strconv.Atoi(segment); err==nil {
isArray=trueif_, err:=container.ArrayCount(segments[:loc]...); err!=nil {
container.Array(segments[:loc]...)
}
ifloc>0 {
if_, err:=container.Set(value, slices.Replace(segments, loc, loc+1, "-")...); err!=nil {
panic(err)
}
} else {
iferr:=container.ArrayAppend(value); err!=nil {
panic(err)
}
}
}
}
if!isArray {
if_, err:=container.SetP(value, path); err!=nil {
panic(err)
}
}
}
// Print the nested JSON as a stringfmt.Println(container.StringIndent("", " "))
}
The trouble is that it doesn't validate the input so you could get some hard to debug issues. For example, if the flattened arrays are not in the right order, then the resulting arrays will not have the expected element order. Also, it doesn't detect gaps in arrays.
I have tried the following with flattened JSON data like
`
flattenedData := map[string]interface{}{
"foo.arr.0": "apple",
"foo.arr.1": "banana",
"oarr.0.id": "id1",
"oarr.1.id": "id2",
}
`
I get
{ "foo": { "arr": { "0": "apple", "1": "banana" } }, "oarr": { "0": { "id": "id1" }, "1": { "id": "id2" } } }
Instead of
{ "foo": { "arr": [ "apple", "banana"] "oarr": [ { "id": "id1" }, { "id": "id2" } ] }
Is there a known way on how I can load this flattened data back into the container? It is using my array indexes as map keys right now.
The text was updated successfully, but these errors were encountered: