Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -2932,6 +2932,7 @@ func init() {
"fromstr": modFromStr,
"group": modGroup,
"dig": modDig,
"key2obj": modKey2Obj,
}
}

Expand Down Expand Up @@ -3147,6 +3148,54 @@ func modValues(json, arg string) string {
return out.String()
}

// @values appends key name as value in child object under "_key"
//
// {"Tom Smith": { "height": 170 ,"weight": 80} } -> {"_key": "Tom Smith", "height": 170 ,"weight": 80} }
func modKey2Obj(json, arg string) string {
v := Parse(json)
if !v.Exists() {
return "[]"
}
if v.IsArray() {
return json
}
var out strings.Builder
out.WriteByte('{')

var i int
v.ForEach(func(rootKey, rootValue Result) bool {
if i > 0 {
out.WriteByte(',')
}
out.WriteString(rootKey.Raw)
out.WriteString(":")

if rootValue.IsObject() {

out.WriteByte('{')

rootValue.ForEach(func(childKey, childValue Result) bool {
out.WriteString(childKey.Raw)
out.WriteString(":")
out.WriteString(childValue.Raw)
out.WriteByte(',')
return true
})
out.WriteString("\"_key\":")
out.WriteString(rootKey.Raw)

out.WriteByte('}')

} else {
out.WriteString(rootValue.Raw)
}
i++
return true
})
out.WriteByte(']')
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

writes { at the start but closes with ]

return out.String()
}

// @join multiple objects into a single object.
//
// [{"first":"Tom"},{"last":"Smith"}] -> {"first","Tom","last":"Smith"}
Expand Down
26 changes: 26 additions & 0 deletions gjson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2727,3 +2727,29 @@ func TestEscape(t *testing.T) {
assert(t, user.Get(Escape("last.name")).String() == "Prichard")
assert(t, user.Get("first.name").String() == "")
}

func TestModKey2Obj(t *testing.T) {
json := `
{
"tickets": {
"ISSUE-10": {
"subject": "foo",
"priority": 1,
"id": 123
},
"ISSUE-12": {
"subject": "bar",
"priority": 3,
"id": 124
},
"ISSUE-17": {
"subject": "baz",
"priority": 2,
"id": 1128
}
}
}
`
assert(t, Get(json, "tickets.@key2obj.@values.#._key").String() == `["ISSUE-10","ISSUE-12","ISSUE-17"]`)
assert(t, Get(json, "tickets.@[email protected]").String() == `{"subject":"foo","priority":1,"id":123,"_key":"ISSUE-10"}`)
}