将文本文件的数据转换为bash

问题描述 投票:0回答:3

我希望在Linux/Bash平台上使用命令以下面的JSON数组格式输出。任何人都可以帮忙

吗?

文本文件中的data

test:test
test1:test1
test4:test4

期望输出:

{array : 
   [
     {test:test},
     {test1:test1}, 
     {test4:test4}
   ]
}
arrays json bash shell
3个回答
4
投票

使用

jq
命令行JSON PARSER:

<file jq -Rs '{array:split("\n")|map(split(":")|{(.[0]):.[1]}?)}'
{
  "array": [
    {
      "test": "test"
    },
    {
      "test1": "test1"
    },
    {
      "test4": "test4"
    }
  ]
}

选项

Rs
jq
读为一个字符串。

脚本将此字符串分为零件以具有预期的格式。


修理您想要实际的JSON输出:

0
投票
split

json-parser

0
投票

XPath:

$ jq -nR '{array: (reduce inputs as $line ([]; . + [$line | split(":") | {(.[0]):.[1]}]))}' input.txt { "array": [ { "test": "test" }, { "test1": "test1" }, { "test4": "test4" } ] }

$ xidel -s "input.txt" -e '
  {
    "array":x:lines($raw) ! {
      substring-before(.,":"):substring-after(.,":")
    }
  }
'

x:lines($raw)
的速记,将每条新行是另一个项目的序列变成一个序列)
XQuery:

tokenize($raw,'\r\n?|\n')

也请参见This XidelcgiDemo.

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.