tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
13.88k stars 841 forks source link

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

Closed mvondentz closed 6 months ago

mvondentz commented 6 months ago

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 commented 6 months ago

I've figured out!

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

Sorry for rubber ducking! Closing this.