Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search / Find #43

Open
Yanik39 opened this issue Mar 5, 2021 · 2 comments
Open

Search / Find #43

Yanik39 opened this issue Mar 5, 2021 · 2 comments

Comments

@Yanik39
Copy link

Yanik39 commented Mar 5, 2021

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)")

@tidwall
Copy link
Owner

tidwall commented Mar 5, 2021

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.

@Yanik39
Copy link
Author

Yanik39 commented Mar 5, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants