Search / Find
Yanik39 opened this issue · comments
Hi,
Lets say;
Json = `{
"name": {"first": "Tom", "last": "Anderson"},
"age":37,
"children": ["Sara","Alex","Jack"],
"fav.movie": "Deer Hunter",
"friends": [
{"first": "James", "last": "Murphy"},
{"first": "Roger", "last": "Craig"}
]
},{
"name": {"first": "Tom", "last": "Anderson"},
"age":35,
"children": ["Sara","Alex","Jack"],
"fav.movie": "Deer Hunter",
"friends": [
{"first": "James", "last": "Murphy"},
{"first": "Roger", "last": "Craig"}
]
}`
this is an array version of the example used at readme, but here first age is 37 and second age is 35
How i can change name.first of age 35?
Is there a search of value like gjson?
Get("#(age==35)")
Is there a search of value like gjson?
The array access character is not allowed with sjson.
How i can change name.first of age 35?
You can use gjson to get the Result
and evaluate the Index
field, and if not zero, that mean the Result
is a slice of the original json, which can then be replaced using sjson.Set
.
For example:
res := gjson.Get(json, "#(age==35)")
if res.Index > 0 {
value, _ := sjson.Set(res.Raw, "name.first", "Jeff")
json = json[:res.Index] + value + json[res.Index+len(res.Raw):]
}
This gets the object that matches #(age==35)
and because Index
is greater than zero we use sjson.Set
on the Raw
result to replace name.first
with "Jeff"
.
Now the json
is updated.
In the future I hope to add this ability directly in sjson
, when time permits.
That is really helpful :D
you saved my day :D