shell 如何使用jq从JSON中获取键名

gg58donl  于 2022-11-16  发布在  Shell
关注(0)|答案(9)|浏览(229)

curl http://testhost.test.com:8080/application/app/version | jq '.version' | jq '.[]'
上述命令仅输出以下值:

"madireddy@test.com"

"2323"

"test"

"02-03-2014-13:41"

"application"

我如何获得密钥名称,而不是像下面:

email

versionID

context

date

versionName
hs1ihplo

hs1ihplo1#

您可以用途:

jq 'keys' file.json

完整示例

$ cat file.json
{ "Archiver-Version" : "Plexus Archiver", "Build-Id" : "", "Build-Jdk" : "1.7.0_07", "Build-Number" : "", "Build-Tag" : "", "Built-By" : "cporter", "Created-By" : "Apache Maven", "Implementation-Title" : "northstar", "Implementation-Vendor-Id" : "com.test.testPack", "Implementation-Version" : "testBox", "Manifest-Version" : "1.0", "appname" : "testApp", "build-date" : "02-03-2014-13:41", "version" : "testBox" }

$ jq 'keys' file.json
[
  "Archiver-Version",
  "Build-Id",
  "Build-Jdk",
  "Build-Number",
  "Build-Tag",
  "Built-By",
  "Created-By",
  "Implementation-Title",
  "Implementation-Vendor-Id",
  "Implementation-Version",
  "Manifest-Version",
  "appname",
  "build-date",
  "version"
]

**UPDATE:**要使用这些键创建BASH数组:

使用BASH 4+:

mapfile -t arr < <(jq -r 'keys[]' ms.json)

在旧版BASH上,您可以执行以下操作:

arr=()
while IFS='' read -r line; do
   arr+=("$line")
done < <(jq 'keys[]' ms.json)

然后打印:

printf "%s\n" "${arr[@]}"

"Archiver-Version"
"Build-Id"
"Build-Jdk"
"Build-Number"
"Build-Tag"
"Built-By"
"Created-By"
"Implementation-Title"
"Implementation-Vendor-Id"
"Implementation-Version"
"Manifest-Version"
"appname"
"build-date"
"version"

或用途:

declare -p arr
ckocjqey

ckocjqey2#

要获取JSON中更深层节点上的键,请执行以下操作:

echo '{"data": "1", "user": { "name": 2, "phone": 3 } }' | jq '.user | keys[]'
"name"
"phone"
y1aodyip

y1aodyip3#

您需要使用jq 'keys[]'。例如:

echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'

将输出一行分隔的列表:

"example1"
"example2"
"example3"
tkclm6bt

tkclm6bt4#

结合上面的答案,你想问jq原始输出,所以你的最后一个过滤器应该是例如:

cat input.json | jq -r 'keys'

来自jq帮助:

-r     output raw strings, not JSON texts;
fae0ux8s

fae0ux8s5#

要以csv格式在一行上打印密钥,请执行以下操作:

echo '{"b":"2","a":"1"}' | jq -r 'keys | [ .[] | tostring ] | @csv'

输出量:

"a","b"

为了csv完整性...将值打印为csv:

echo '{"b":"2","a":"1"}' | jq -rS . | jq -r '. | [ .[] | tostring ] | @csv'

输出量:

"1","2"
bqujaahr

bqujaahr6#

如果输入是对象数组,

[
  { 
    "a01" : { "name" : "A", "user" : "B" }
  },
  { 
    "a02" : { "name" : "C", "user" : "D" }
  }
]

尝试使用:

jq '.[] | keys[]'
wnvonmuf

wnvonmuf7#

echo '{"ab": 1, "cd": 2}' | jq -r 'keys[]'打印所有键,每行一个键,不带引号。

ab
cd
oxalkeyp

oxalkeyp8#

奇怪的是,公认的答案实际上并没有准确回答问题,因此,作为参考,这里有一个解决方案可以做到这一点:

$ jq -r 'keys_unsorted[]' file.json
hfyxw5xn

hfyxw5xn9#

下面是获取Bash数组的另一种方法,使用@anubhava在他的答案中给出的JSON示例:

arr=($(jq --raw-output 'keys_unsorted | @sh' file.json))

echo ${arr[0]}    # 'Archiver-Version'
echo ${arr[1]}    # 'Build-Id'
echo ${arr[2]}    # 'Build-Jdk'

相关问题