tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.4k stars 858 forks source link

String templating? #373

Closed adaml881 closed 1 month ago

adaml881 commented 1 month ago

Is there a way to join properties into a single property on the output?

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

Using this example, I'd like to be able to get an output this from the friends array

[
   "[first] [last] Aged [age]"
]

Example:

[
  "Dale Murphy Aged 44",
  "Roger Craig Aged 68",
  "Jane Murphy Aged 47"
]
volans- commented 1 month ago

@adaml881 not that I know of, but you could wrote a simple custom modifier (see docs) that joins all the array elements with space and returns a string. Then you could use a query like this one using multipaths to create the array of elemens you want and use your modifier:

friends.#.[first,last,!"Aged",age].@spacejoin

the above query without the modifier would output:

[["Dale","Murphy","Aged",44],["Roger","Craig","Aged",68],["Jane","Murphy","Aged",47]]

Using the dot instead of the pipe will apply the modifier to each inner array.

adaml881 commented 1 month ago

Amazing, thank you