使用jq将JSON对象转换为Prometheus指标格式 [英] convert JSON object to Prometheus metrics format using jq

查看:375
本文介绍了使用jq将JSON对象转换为Prometheus指标格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑类似JSON对象

{
  "foo": 42,
  "baz": -12,
  "bar{label1=\"value1\"}": 12.34
}

jq 构造,并使用了一些数据源.实际的键名及其数量可能有所不同,但结果始终是一个以数字(整数或浮点数)为值的对象.这些键可以包含引号,但不能包含空格.

constructed by jq using some data source. The actual key names and their amount may vary, but the result will always be an object with numbers (int or float) as values. The keys may contain quotation marks, but no whitespaces.

我可以使用jq将对象格式化为兼容 Prometheus 的格式,这样我就可以使用输出来将数据推送到Prometheus Pushgateway?

Can I use jq to format the object into a Prometheus-compatible format so I can just use the output to push the data to a Prometheus Pushgateway?

所需的结果看起来像

foo 42
bar{label1="value1"} 12.34
baz -12

即用换行符分隔的空格(不带\r),除了标签值外,不带引号.

i.e. space-separated with newlines (no \r) and without quotes except for the label value.

我不能使用bash进行后处理,因此,如果可能的话,我希望使用纯jq解决方案.

I can't use bash for post-processing and would therefore prefer a pure jq solution if possible.

推荐答案

使用keys_unsorted获取对象键(keys的作用相同,但前者更快),通过字符串插值生成所需的输出.

Use keys_unsorted to get object keys (keys does the same as well but the former is faster), generate desired output by means of string interpolation.

$ jq -r 'keys_unsorted[] as $k | "\($k) \(.[$k])"' file
foo 42
baz -12
bar{label1="value1"} 12.34

而且,通过添加-j选项并按照@peak的建议手动打印换行符,可以使它变得可移植.

And, by adding -j option and printing line feed manually as @peak suggested you can make this portable.

这篇关于使用jq将JSON对象转换为Prometheus指标格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆