Skip to content

feat(read): support array index path in Get, eg. parent.child[1] - #231

Merged
inhere merged 1 commit into
gookit:masterfrom
saromanov:feat/get-array-index-path
Oct 27, 2026
Merged

inhere merged 1 commit into
gookit:masterfrom
saromanov:feat/get-array-index-path

Conversation

@saromanov

Copy link
Copy Markdown
Contributor

Closes the remaining gap of #96: setting array elements by path with an
index (Set("parent.child[0]", ...)) already works today (via maputil.SetByKeys,
verified against goutil v0.8.3), but reading them back with the same syntax
did not - Get("parent.child[1]") returned nothing, since only the
dot-index form (parent.child.1) was understood.

GetValue and Exists now expand trailing [N] markers in path segments:

c.Set("parent.child[0]", "Test1")
c.Set("parent.child[1]", "Test2")
c.Get("parent.child[1]") // "Test2"
c.Get("db.replicas[1].host") // nested: array element, then map key

Details:

  • the top-level key is never expanded, so literal top-level keys containing
    brackets keep working;
  • segments with a non-numeric bracket (child[x]) are treated as literal
    keys, as before;
  • multiple trailing indexes per segment are supported (matrix[0][1]);
  • the dot-index style (parent.child.1) is unchanged.

Tests cover set/get round-trip, nested paths, out-of-range/negative indexes,
non-numeric indexes and the Exists parity.

Closes #96

@inhere
inhere merged commit 87302e0 into gookit:master Oct 27, 2026
12 checks passed
inhere added a commit that referenced this pull request Oct 29, 2026
GetValue and Exists each carried the same hand-written path walk next to the
bracket-index expansion added in #231, while gookit/goutil resolves the whole
path now (bracket indexes, literal keys matched first, typed maps since v0.8.6).

- GetValue and Exists delegate to maputil.GetByPathKeys, so the local
  expandKeyIndexes/expandSegIndex helpers and both walks are gone.
- recordGetPathError keeps the old error report: a path that runs into a value
  which cannot have sub-keys still records "cannot get value of the key 'x'",
  while a missing key stays silent.
- a non-numeric index into a slice (eg. "arr1.notExist") is a plain not-found
  now instead of a recorded strconv error.
- bump github.com/gookit/goutil to v0.8.6, which resolves map[string]int and
  other typed maps that Set() may store.

Tests: the existing suite covers the array index paths, the map[string]int
values, Exists parity and the top-level literal key; no assertion changed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEAT] Support Set with Slice (Array) Index Using Square Brackets?

2 participants