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

How to apply multipaths to all elements of an array #344

Closed
mvondentz opened this issue Dec 29, 2023 · 1 comment
Closed

How to apply multipaths to all elements of an array #344

mvondentz opened this issue Dec 29, 2023 · 1 comment

Comments

@mvondentz
Copy link

mvondentz commented Dec 29, 2023

Hi!

I'm trying to construct a new json using multipaths and literals to create new keys.
It is working nicely!
Ex.

jsonData := `{
      "age":37,
      "children": ["Sara","Alex","Jack"],
      "fav.movie": "Deer Hunter",
      "friends": [
          {"age": 44, "first": "Dale", "last": "Murphy"},
          {"age": 68, "first": "Roger", "last": "Craig"},
          {"age": 47, "first": "Jane", "last": "Murphy"}
      ],
      "name": {"first": "Tom", "last": "Anderson"}
  }`

path := `{"newAge":age,"Sara":children.0}`
transformedData := gjson.Get(jsonData, path)
fmt.Println(transformedData.String())

But I'm struggling on how to achieve the same result for json objects inside an array (not sure if possible).
Considering the following json:

{
      "age":37,
      "children": ["Sara","Alex","Jack"],
      "fav.movie": "Deer Hunter",
      "friends": [
          {"age": 44, "first": "Dale", "last": "Murphy"},
          {"age": 68, "first": "Roger", "last": "Craig"},
          {"age": 47, "first": "Jane", "last": "Murphy"}
      ],
      "name": {"first": "Tom", "last": "Anderson"}
}

Is there a way in which I can construct a new array that is based on the friends only using multipaths and literal expressions? To return something like:

[
  {
    "coolAge": 44,
    "name": "Dale"
  },
  {
    "coolAge": 68,
    "name": "Roger"
  },
  {
    "coolAge": 47,
    "name": "Jane"
  }
]

Thanks!

@mvondentz
Copy link
Author

I've figured out!

{friends.#.{"coolAge":age, "name":first}}

Sorry for rubber ducking! Closing this.

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

1 participant