Closed iamshreeram closed 3 years ago
There's currently no way to do all that with a single query.
Perhaps a combination of gjson
and sjson
.
package main
import (
"fmt"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
func main() {
json := `
{
"app": "gfgeeks",
"prop": [
{"region": 736,"set": true,"score": 72},
{"region": 563,"set": true,"score": 333},
{"region": 563,"set": false,"score": 333}
],
"index" : "haskell"
}`
// loop through the "prop" values and find the target
var index int
var found bool
gjson.Get(json, "prop").ForEach(func(_, value gjson.Result) bool {
if value.Get("region").Int() == 563 && value.Get("set").Bool() {
found = true
return false
}
index++
return true
})
if found {
// if found the use sjson to update the value at index
json, _ = sjson.Set(json, fmt.Sprintf("prop.%d.score", index), 334)
}
println(json)
}
Outputs:
{
"app": "gfgeeks",
"prop": [
{"region": 736,"set": true,"score": 72},
{"region": 563,"set": true,"score": 334}, // modified score to 334
{"region": 563,"set": false,"score": 333}
],
"index" : "haskell"
}
Perfect. Thanks!
Hi, My use case is to
Below is the sample payload -
I want to modify the payload to below based on 2 condition ( "region": 563 & "set": true )
As part of this, I'm trying to get the map from list of map
gjson.Get
instead of actual valueregion
is same asregionid
and alsoset
istrue
. Something likefmt.Println(gjson.Get(json, "prop|#(region=regionid)#|#(set=true)#"))
score
with different value / variable and update that back to main payloadprop.#.region
I'm unable to convert theResult
interface to integer withResult.Int()
. Below is the errorNote: The
props
list in this example is small. But, real world list has multiple elements. If above is a expensive approach, Any suggestion to get this smarter is much appreciated. Thanks!cc: @tidwall