2

Is it possible to convert this JSON:

{ "message": "Hello!", "contextMap": { "foo": 1, "bar": 2, ...otherInContextMap }, ...someOther }

(where keys of contextMap are not known) into the following JSON:


{ "message": "Hello!", "foo": 1, "bar": 2, ...otherInContextMap  }

using JMESPath?

(Context: I want to scrape Java logs with contextMap using Promtail and store message together with members of contextMap to Loki.)

EDIT: I need to explicitly pick message and members of contextMap. (There are some other unknown/dynamic members ...someOther in JSON.)

TN.
  • 18,874
  • 30
  • 99
  • 157

1 Answers1

1

You can merge a basic query selecting the content of contextMap along with a multiselect hash for the message.

So, given the query:

merge({message: message}, contextMap)

On your given input, it would yield the expected:

{
  "message": "Hello!",
  "foo": 1,
  "bar": 2
}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
  • +1 Thank you! It seems that `merge` will fail, if `contextMap` is not present (at least in go-jmespath: `interface conversion: interface {} is nil, not map[string]interface {}`). Is it possible to tweak merge not to fail? – TN. Aug 25 '22 at 09:56
  • Odd, merging `null` (which is what a basic query on a field that does not exists should do) to an object should work. Does, doing an ugly thing like `merge({message: message}, to_array(@)[?contextMap].contextMap | [0])` fixes it? – β.εηοιτ.βε Aug 25 '22 at 10:02
  • Another thing to try could be: `merge({message: message}, {contextMap: contextMap}.contextMap)` – β.εηοιτ.βε Aug 25 '22 at 10:11
  • No:( See https://go.dev/play/p/eeAEThlGGrk – TN. Aug 25 '22 at 10:25
  • 1
    Final solution is ```merge({message: message}, not_null(contextMap, `{}`))```. – TN. Aug 25 '22 at 10:47
  • 1
    For the sake of the community, would you please report that issue on their tracker: https://github.com/jmespath/go-jmespath/issues. Expected behaviour, is that ```merge(`{"a": 1}`, null)``` should yield `{"a": 1}` – β.εηοιτ.βε Aug 25 '22 at 10:47