MCPcopy Create free account
hub / github.com/PerpetualSoftware/pad / FirstDuplicateJSONKey

Function FirstDuplicateJSONKey

internal/models/json_duplicate_keys.go:24–79  ·  view source on GitHub ↗

FirstDuplicateJSONKey reports the first object member name that appears twice in the same object, at any depth. It walks EVERY depth: each object on the token stack keeps its own set of member names, so {"a":1,"a":2} and {"x":{"k":1,"k":2}} are both reported, and a name repeated in two DIFFERENT ob

(raw []byte)

Source from the content-addressed store, hash-verified

22// and a decode error there is the caller's to report, not this function's to
23// duplicate.
24func FirstDuplicateJSONKey(raw []byte) (string, bool) {
25 type frame struct {
26 isObject bool
27 seen map[string]bool
28 expectKey bool
29 }
30 var stack []*frame
31 top := func() *frame {
32 if len(stack) == 0 {
33 return nil
34 }
35 return stack[len(stack)-1]
36 }
37
38 dec := json.NewDecoder(bytes.NewReader(raw))
39 for {
40 tok, err := dec.Token()
41 if err != nil {
42 return "", false // EOF, or malformed — nothing to report either way.
43 }
44 if d, isDelim := tok.(json.Delim); isDelim {
45 switch d {
46 case '{':
47 stack = append(stack, &frame{isObject: true, seen: map[string]bool{}, expectKey: true})
48 case '[':
49 stack = append(stack, &frame{})
50 case '}', ']':
51 if len(stack) > 0 {
52 stack = stack[:len(stack)-1]
53 }
54 // The container that just closed WAS a value of its parent, so
55 // the parent's next token is a key again.
56 if f := top(); f != nil && f.isObject {
57 f.expectKey = true
58 }
59 }
60 continue
61 }
62 f := top()
63 if f == nil || !f.isObject {
64 continue
65 }
66 if f.expectKey {
67 if name, isString := tok.(string); isString {
68 if f.seen[name] {
69 return name, true
70 }
71 f.seen[name] = true
72 }
73 f.expectKey = false
74 continue
75 }
76 // A scalar value; the next token in this object is a key.
77 f.expectKey = true
78 }
79}
80
81// CollapseDuplicateJSONKeys returns an item fields blob unchanged when no

Callers 6

importWorkspaceMethod · 0.92
repairBodyNULEscapesFunction · 0.92

Calls 1

appendFunction · 0.85

Tested by 2