sjson icon indicating copy to clipboard operation
sjson copied to clipboard

Search / Find

Open Yanik39 opened this issue 4 years ago • 2 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)")

Yanik39 avatar Mar 05 '21 20:03 Yanik39

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.

here's a working example

In the future I hope to add this ability directly in sjson, when time permits.

tidwall avatar Mar 05 '21 21:03 tidwall

That is really helpful :D you saved my day :D

Yanik39 avatar Mar 05 '21 21:03 Yanik39