ohler55/ojg

Feature Request: enable copy and move of jpath to other parts of hierarchy

Closed this issue · 2 comments

The use case we have is the need to pull up key/values in a subfield to a parent field (without deleting existing fields).

{
  "foo": "bar",
  "baz": "buz",
  "ext": {
    "abc": "def"
    "ghi": 123
  }
}

should be able to copy, move or merge ext to $ concisely and end up with:

{
  "foo": "bar",
  "baz": "buz",
  "abc": "def"
  "ghi": 123
}

Due to the various options needed to avoid overwriting top level elements that exist with the same name it's not really appropriate to put this in the ojg/jp package itself. If you are not worried about name collisions then something like this should do what you describe.

	data := oj.MustParseString(`{
  "foo": "bar",
  "baz": "buz",
  "ext": {
    "abc": "def"
    "ghi": 123
  }
}
`)
	flat := map[string]any{}
	jp.Walk(data, func(path Expr, value any) {
		if c, ok := path[len(path)-1].(jp.Child); ok {
			flat[string(c)] = value
		}
	}, true)

With both jp.Locate() and jp.Walk() functions available it should be easy enough to make a custom function for flattening.

Since there has been no response or activity here for 2 weeks, this issue will be closed.