JQ使用bash创建json数组 [英] JQ create json array using bash

查看:147
本文介绍了JQ使用bash创建json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在尝试获取有关我的文件托管帐户的信息.由于我将许多备份媒体保留在不同的帐户中.我正在使用megatools查询有关该帐户的信息,然后将其解析为一个数组.然后使用\ n将该数组展平为原始输入.

I am currently trying to get information about my file hosting accounts. As I keep a lot of my backup media on different accounts. I am using megatools to query information about the account, which I then parse into an array. The array is then flattened using \n for raw input.

该脚本运行出色,但是无法创建有效的json.我不确定我要使它有效所缺少的内容.感谢您的提前帮助.

The script works wonderfully but its not creating valid json. I am not sure what I am missing to make it valid. Thanks for the help in advance.

脚本

function join_by { local IFS="$1"; shift; echo "$*"; }

while IFS='' read -r line || [[ -n "$line" ]]; do
    IFS=, read -ra array <<< "$line"

    nickname=${array[0]}
    user=${array[1]}
    pass=${array[2]}
    data=($(megadf --username=$user --password=$pass))
    data[${#data[@]}]+="$nickname"

    stats=$(join_by $'\n' ${data[@]})

    echo $stats | jq --slurp --raw-input 'split("\n")[:-1] | map([ split(" ")[] ]) | map({
    nick: .[6],
    total: .[1],
    used: .[3],
    free: .[5]
    })' >> /opt/stats/json/accounts.json

done < .accounts

json输出

[
  {
    "nick": "alt",
    "total": "53687091200",
    "used": "7885201595",
    "free": "45801889605"
  }
]
[
  {
    "nick": "main",
    "total": "214748364800",
    "used": "87240914483",
    "free": "127507450317"
  }
]

应该是什么

[
  {
    "nick": "alt",
    "total": "53687091200",
    "used": "7885201595",
    "free": "45801889605"
  },
  {
    "nick": "main",
    "total": "214748364800",
    "used": "87240914483",
    "free": "127507450317"
  }
]

.帐户

nickname,user,pass

推荐答案

@barmar找到了我忽略的最简单的解决方案....

@barmar found the simplest solution that I overlooked....

需要将循环传递到jq

Needed to pipe the loop into jq

while IFS='' read -r line || [[ -n "$line" ]]; do
    IFS=, read -ra array <<< "$line"
    nickname=${array[0]}
    user=${array[1]}
    pass=${array[2]}
    data=($(megadf --username=$user --password=$pass))
    data[${#data[@]}]+="$nickname"
    stats=$(join_by $'\n' ${data[@]})
    echo $stats
done < .accounts  | jq --slurp --raw-input 'split("\n")[:-1] | map([ split(" ")[] ]) | map({
    nick: .[6],
    total: .[1],
    used: .[3],
    free: .[5]
    })' >> /opt/stats/json/accounts.json

这篇关于JQ使用bash创建json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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