使用命令行工具将JSON数组拆分为多个文件

ttygqcqt  于 2023-05-02  发布在  其他
关注(0)|答案(5)|浏览(190)

假设我们有一个长度为5的JSON数组,我们想使用linux命令行工具将该数组拆分为多个长度为2的数组,并将分组的项目保存到不同的文件中。
我使用jqsplit工具进行了尝试(我对任何可以从bash脚本执行的方法都很满意):

$ echo '[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"},{"key4":"value4"},{"key5":"value5"}]' | jq -c -M '.[]' | split -l 2 -d -a 3 - meta_
$ tail -n +1 meta_*
==> meta_000 <==
{"key1":"value1"}
{"key2":"value2"}

==> meta_001 <==
{"key3":"value3"}
{"key4":"value4"}

==> meta_002 <==
{"key5":"value5"}

前面的命令将项正确地保存到文件中,但是我们需要将它们转换为有效的JSON数组格式。我用--filter选项累了:

$ echo '[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"},{"key4":"value4"},{"key5":"value5"}]' | jq -c -M '.[]' | split -l 2 -d -a 3 - meta2_ --filter='jq --slurp -c -M'
[{"key1":"value1"},{"key2":"value2"}]
[{"key3":"value3"},{"key4":"value4"}]
[{"key5":"value5"}]
$ tail -n +1 meta2_*
tail: cannot open 'meta2_*' for reading: No such file or directory

但是,它会在屏幕上显示输出,但不会持久保存结果。我尝试转发输出,但得到一个错误:

echo '[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"},{"key4":"value4"},{"key5":"value5"}]' | jq -c -M '.[]' | split -l 2 -d -a 3 - meta2_ --filter='jq --slurp -c -M > $FILE'
...
split: with FILE=meta2_000, exit 2 from command: jq --slurp -c -M > $FILE

有什么建议或更好的方法吗?
编辑:我尝试了双引号@andlrc建议:

$ echo '[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"},{"key4":"value4"},{"key5":"value5"}]' | jq -c -M '.[]' | split -l 2 -d -a 3 - meta2_ --filter="jq --slurp -c -M > $FILE"
bash: -c: line 0: syntax error near unexpected token `newline'
bash: -c: line 0: `jq --slurp -c -M > '
split: with FILE=meta2_000, exit 1 from command: jq --slurp -c -M >
$ cat meta_000 | jq --slurp -c -M
[{"key1":"value1"},{"key2":"value2"}]
uubf1zoe

uubf1zoe1#

在jq过滤器中构建数组会更容易,然后每行拆分为文件。无需额外过滤。

range(0; length; 2) as $i | .[$i:$i+2]

生产:

[{"key1":"value1"},{"key2":"value2"}]
[{"key3":"value3"},{"key4":"value4"}]
[{"key5":"value5"}]

所以把这些都放在一起。

$ jq -cM --argjson sublen '2' 'range(0; length; $sublen) as $i | .[$i:$i+$sublen]' \
    input.json | split -l 1 -da 3 - meta2_
eoigrqb6

eoigrqb62#

我使用jqsplit工具找到了解决方案。我缺少了双引号,jq中的'.'模式,并用反斜杠来修饰$

$ echo '[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"},{"key4":"value4"},{"key5":"value5"}]' |
  jq -c -M '.[]' |
  split -l 2 -d -a 3 - meta2_ --filter="jq --slurp -c -M '.' >\$FILE"
$ tail -n +1 meta2_*
==> meta2_000 <==
[{"key1":"value1"},{"key2":"value2"}]

==> meta2_001 <==
[{"key3":"value3"},{"key4":"value4"}]

==> meta2_002 <==
[{"key5":"value5"}]
lvjbypge

lvjbypge3#

  • 假设我们有一个长度为5的JSON数组,我们想将该数组拆分为多个长度为2的数组,并将分组后的项目保存到不同的文件中,使用linux命令行工具。*

JSON解析器xidel可以做您想要的事情,并且可以执行XQuery 3。1 FLWOR表达式与(翻转)Window子句的基本思想是:

$ xidel -se '
  for tumbling window $w in 1 to 5
  start $s when $s mod 2 eq 1
  return
  join($w)
'
1 2
3 4
5

$ echo '[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"},{"key4":"value4"},{"key5":"value5"}]' | \
  xidel -se '
  for tumbling window $w in 1 to count($json())
  start $s when $s mod 2 eq 1
  return
  array{$w ! $json(.)}
' --output-json-indent=compact
[{"key1": "value1"}, {"key2": "value2"}]
[{"key3": "value3"}, {"key4": "value4"}]
[{"key5": "value5"}]

要将每个数组保存为json文件,您可以使用Xidel的集成EXPath文件模块:

$ xidel -se '
  for tumbling window $w in 1 to 5
  start $s at $i when $s mod 2 eq 1
  count $i
  return
  x"output_{$i}.json - {join($w)}"
'
output_1.json - 1 2
output_2.json - 3 4
output_3.json - 5

$ echo '[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"},{"key4":"value4"},{"key5":"value5"}]' | \
  xidel -se '
  for tumbling window $w in 1 to count($json())
  start $s at $i when $s mod 2 eq 1
  count $i
  return
  file:write(
    x"output_{$i}.json",
    array{$w ! $json(.)},
    {"method":"json"}
  )
'

$ xidel -s output_1.json output_2.json output_3.json -e '$raw'
$ xidel -s output_1.json output_2.json output_3.json -e '$json' --output-json-indent=compact
[{"key1":"value1"},{"key2":"value2"}]
[{"key3":"value3"},{"key4":"value4"}]
[{"key5":"value5"}]
d8tt03nd

d8tt03nd4#

jq可能是其他回答中提到的方法。因为我对jq不熟悉,所以我写了一个bash脚本(splitjson)。sh)下面使用非常常见的命令(echo,cat,wc,head,tail,sed,expr)。此脚本将json文件拆分为不超过指定字节数的块。如果在指定的字节数内无法进行拆分(json项很长或每个块指定的最大字节数太小),脚本将停止写入json文件并写入错误。
下面是一个例子,以问题中的数据为例。json:

[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"},{"key4":"value4"},{"key5":"value5"}]

执行每个块具有最大字节数的脚本的命令是:

$ ./splitjson.sh example.json 40

结果是:

$ head example.json.*
==> example.json.0 <==
[{"key1":"value1"},{"key2":"value2"}]
==> example.json.1 <==
[{"key3":"value3"},{"key4":"value4"}]
==> example.json.2 <==
[{"key5":"value5"}]

该脚本处理结尾括号'}'、冒号','和开始括号'|'之间带有空格、制表符和换行符的情况。
我成功地在82 MB的json文件上使用了这个脚本。我希望它能处理更大的文件。
下面是脚本(splitjson.sh):

#!/bin/bash
if [ $# -ne 2 ]
then
    echo "usage: $0 file_to_split.json nb_bytes_max_per_split"
    exit 1
fi
if [[ -r $1 ]]
then
    input=$1
    echo "reading from file '$input'"
else
    echo "cannot read from specified input file '$1'"
    exit 2
fi
if [[ $2 = *[[:digit:]]* ]]; then
    maxbytes=$2
    echo "taking maximum bytes '$maxbytes'"
else
    echo "provided maximum number of bytes '$2' is not numeric"
    exit 3
fi

start=0
over=0
iteration=0
inputsize=`cat $input|wc -c`
tailwindow="$input.tail"
echo "input file size: $inputsize"
tmp="$input.tmp"
cp $input $tmp
sed -e ':a' -e 'N' -e '$!ba' -e 's/}[[:space:]]*,[[:space:]]*{/},{/g' -i'.back' $tmp
rm "$tmp.back"
inputsize=`cat $tmp|wc -c`
if [ $inputsize -eq 0 ]; then
    cp $input $tmp
    sed -e 's/}[[:space:]]*,[[:space:]]*{/},{/g' -i'.back' $tmp
    rm "$tmp.back"
fi
inputsize=`cat $tmp|wc -c`
while [ $over -eq 0 ]; do
    output="$input.$iteration"
    if [ $iteration -ne 0 ]; then
                echo -n "[{">$output
    else
                echo -n "">$output
    fi
    tailwindowsize=`expr $inputsize - $start`
    cat $tmp|tail -c $tailwindowsize>$tailwindow
    tailwindowresultsize=`cat $tailwindow|wc -c`
    if [ $tailwindowresultsize -le $maxbytes ]; then
        cat $tailwindow>>$output
        over=1
    else
        cat $tailwindow|head -c $maxbytes|sed -E 's/(.*)\},\{(.*)/\1}]/'>>$output
    fi
    jsize=`cat $output|wc -c`
    start=`expr $start + $jsize`
    if [ $iteration -eq 0 ]; then
        start=`expr $start + 1`
    else
        start=`expr $start - 1`
    fi
    endofj=`cat $output|tail -c 3`
    if [ $over -ne 1 ]; then
        if [ ${endofj:1:2} != "}]" ]; then
            if [ ${endofj:0:2} != "}]" ]; then
                echo -e "ERROR: at least one split pattern wasn't found. Aborting. This could be due to wrongly formatted json or due to a json entry too long compared to the provided maximum bytes. Maybe you should try increasing this parameter?\a"
                exit 4
            fi
        fi
    fi
    jsizefinal=`cat $output|wc -c`
    echo "wrote $jsizefinal bytes of json for iteration $iteration to $output"
    iteration=`expr $iteration + 1`
done
rm $tailwindow
rm $tmp
q7solyqu

q7solyqu5#

拆分为两个单独的jq调用允许第二个调用使用input帮助程序一次只处理一个输入。在第二个例子中使用try帮助器可以让它优雅地处理不完整的行,如果您没有剩下两个输入项的话。

s='[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"},{"key4":"value4"},{"key5":"value5"}]'

jq '.[]' <<<"$s" | \
  jq -c -n 'repeat(input as $i1 | try (input as $i2 | [$i1, $i2]) catch [$i1])?' | \
  split -l 2 -d -a 3 - meta_

...发出,在第一个文件中:

[{"key1":"value1"},{"key2":"value2"}]
[{"key3":"value3"},{"key4":"value4"}]

......在第二种情况下:

[{"key5":"value5"}]

相关问题