漂亮打印的有效 JSON 与字符串键混合

Pretty-print valid JSONs mixed with string keys

我有一个 Redis 散列,其中包含键和值,例如字符串键 -- 序列化 JSON 值。 相应的 rediscli 查询 (hgetall some_redis_hash) 被转储到文件中:

redis_key1
{"value1__key1": "value1__value1", "value1__key2": "value1__value2" ...}
redis_key2
{"value2__key1": "value2__value1", "value2__key2": "value2__value2" ...}
...
and so on.

所以问题是,我如何漂亮地打印括号中的这些值? (请注意,如果您尝试解析整个文档,则它们之间的关键字符串会使文档无效) 第一个想法是从 Redis 中获取特定的对,剥离寄生键,并在剩余的有效 JSON 上使用 jq,如下所示:

rediscli hget some_redis_hash redis_key1 > file && tail -n +2 file
- file now contains valid JSON as value, the first string representing Redis key is stripped by tail -
cat file | jq
- produces pretty-printed value -

那么问题来了,如何在没有这种预处理的情况下进行漂亮的打印? 或者(在这种特殊情况下会更好)如何将键和值合并到一个大 JSON 中,其中 Redis 键可在上层访问,其后将跟随其值的字典? 像那样:

rediscli hgetall some_redis_hash > file
cat file | cool_parser
- prints { "redis_key1": {"value1__key1": "value1__value1", ...}, "redis_key2": ... }

一个简单的漂亮打印方法如下:

cat file | jq --raw-input --raw-output '. as $raw | try fromjson catch $raw'

它尝试将每一行解析为 json 和 fromjson,如果不能,则只输出原始行($raw)。

(那里有 --raw-input,这样我们就可以调用包含在 try 中的 fromjson,而不是直接在每一行调用 运行,并且 --raw-output 在那里,因此任何非 json 行都不会在输出中用引号引起来。)


仅使用 jq 解决问题第二部分的方法:

cat file \
    | jq --raw-input --null-input '[inputs] | _nwise(2) | {(.[0]): .[1] | fromjson}' \
    | jq --null-input '[inputs] | add'
  • --null-input[inputs] 结合生成整个输入作为数组
  • 然后 _nwise(2) 分成两个组 ()
  • 然后 {(.[0]): .[1] | fromjson} 转换为 jsons
  • 的列表
  • 然后 | jq --null-input '[inputs] | add' 组合成一个 json

或在单个 jq 调用中:

cat file | jq --raw-input --null-input \
    '[ [inputs] | _nwise(2) | {(.[0]): .[1] | fromjson} ] | add'

...但到那时,您最好编写一个更易于理解的 python 脚本。