zoukankan      html  css  js  c++  java
  • Linux 命令详解(十一)Shell 解析 json命令jq详解

    前言

    在自动化部署中涉及到shell脚本需要动态读取很多配置文件,最好是json格式。

    更多jq信息: http://stedolan.github.io/jq/manual/

    一、根据key获取value

    语法:jq '.key'

    1、单个值获取

    www@TinywanAliYun:~$ cat d25341478381063d1c76e81b3a52e0592a7c997f.json | jq '.sign'
    "d25341478381063d1c76e81b3a52e0592a7c997f"

    2、JSON nested parse(嵌套解析)

    www@TinywanAliYun:~$ cat d25341478381063d1c76e81b3a52e0592a7c997f.json | jq '.live_node_config.node1.ip'
    "192.168.10.10"

    注意:json 数组的键命名必须为下划线"_",不能为"-",否则解析不了。如:

    错误的命名

      "live-node-proxy-config": {
        "ip": "192.168.10.100",
        "user": "www",
        "pwd": "www123456"
      },

    正确

      "live_node_proxy_config": {
        "ip": "192.168.10.100",
        "user": "www",
        "pwd": "www123456"
      },

    小菜刀!!!在这里我们可以使用curl可以获取完全一样的结果

    www@TinywanAliYun:~$ curl -s 'https://www.tinywan.com/frontend/websocket_client/autoInstallConf' | jq '.live_node_config.node1.ip'
    "192.168.10.10"

    curl 的 -s 参数表示:静默模式。不输出任何东西,更多了解【curl命令

    在这里如果不加该参数则会输出文件下载进度,如下所示:

    www@TinywanAliYun:~$ curl 'https://www.tinywan.com/frontend/websocket_client/autoInstallConf' | jq '.live_node_config.node1.ip'
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   636    0   636    0     0   2053      0 --:--:-- --:--:-- --:--:--  2058
    "192.168.10.10"

    3、解析不存在的元素,会返回null

    www@TinywanAliYun:~$ cat d25341478381063d1c76e81b3a52e0592a7c997f.json | jq '.live_node_config.node1.ip123'
    null

     

    二、jq的内建函数,如:keys,has

    1、keys是用来获取JSON中的key元素的,查找json中所有的键

    www@TinywanAliYun:$ curl 'https://www.tinywan.com/frontend/websocket_client/autoInstallConf' | jq 'keys'
    [
      "live-node-config",
      "live-node-proxy-config",
      "osscmd-config",
      "push-config",
      "redis-config",
      "sign"
    ]

    2、has是用来是判断是否存在某个key

    www@TinywanAliYun:~$ curl 'https://www.tinywan.com/frontend/websocket_client/autoInstallConf' | jq 'has("sign")'
    true
    www@TinywanAliYun:~$ curl 'https://www.tinywan.com/frontend/websocket_client/autoInstallConf' | jq 'has("sign2")'
    false
    www@TinywanAliYun:~$

     

  • 相关阅读:
    C# STUDY
    C# 通过线程来控制进度条(转)--讲解多线程对界面的操作
    Android开发问题笔记
    win7 Android环境搭配
    Git-Flow
    Synchronizing with Remote Repositories
    smartgit document merge
    smartgit document Rebase
    手把手教你玩转Git分布式版本控制系统!
    (二)代理模式详解(包含原理详解)
  • 原文地址:https://www.cnblogs.com/tinywan/p/7684414.html
Copyright © 2011-2022 走看看