使用jq从JSON获取键和值 [英] Using jq to get key and value from JSON

查看:91
本文介绍了使用jq从JSON获取键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是curl <url> | jq '.'

{
 "63": {
    "state": {
      "on": false,
      "alert": "select",
      "mode": "automation",
      "reachable": true
    },
    "swupdate": {
      "state": "notupdatable",
      "lastinstall": "2019-09-15T11:19:15"
    },
    "type": "plug",
    "name": "Tree",
    "modelid": "XXX",
    "manufacturername": "XXX",
    "productname": "plug",
    "capabilities": {
      "certified": false,
      "control": {},
      "streaming": {
        "renderer": false,
        "proxy": false
      }
    },
    "config": {
      "archetype": "plug",
      "function": "functional",
      "direction": "omnidirectional"
    },
    "uniqueid": "00:0d:6f:ff:fe:da:c9:dc-01",
    "swversion": "2.0.022"
  }
}

我想将输出传递给jq,以便我可以从每个对象返回键和名称,例如"63"树"(我不担心结果是否在括号中,或者如何分隔字段,或者是否包括"name":.)

I want to pipe the output to jq so that I can return the key and name from each object, e.g. "63" "Tree" (I am not concerned if the result is in parentheses or how the fields are separated or whether "name": is included.)

我可以获得钥匙: curl <url> | jq -r 'keys[]'

和名称: curl <url> \ jq -r '.[]{"name"}

但是我不能将它们放在同一行.

but I can't get them both on the same line.

推荐答案

一种简洁有效的解决方案,有些人会说优雅:

A succinct, efficient, and some would say elegant, solution:

map_values(.name)

众多选择之一:

with_entries( {key, value: .value.name} )

如果您希望所有内容都在一行上,则可以使用-c命令行选项.

If you want everything on a single line, you could use the -c command-line option.

这篇关于使用jq从JSON获取键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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