如何打印JSON字符串的一部分并将其存储在变量中? [英] How to print a part of a JSON string and store it in variable?

查看:182
本文介绍了如何打印JSON字符串的一部分并将其存储在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用curl创建会话以登录到交换机。
我使用的脚本下面

I am using curl to create a session to log into the switch. Below the script that i use

curl --noproxy 10.23.193.1 -X POST http://10.23.193.1:80/rest/v3/login-sessions -d '{"userName":"admin", "password":"password"}'

执行此操作后,我得到以下输出

After this is executed I get the following output

{"uri":"/login-sessions","cookie":"sessionId=DfZNCFbfoc3LDuMgjLXRiS8ZmEo4MWENCOJM0Iu14R1uMT9kKqbe1Rx6AedmoeT"}



<首先只打印字符串的这一部分 sessionId = DfZNCFbfoc3LDuMgjLXRiS8ZmEo4MWENCOJM0Iu14R1uMT9kKqbe1Rx6AedmoeT

要第二次存储上面的字符串在变量中,以便我可以为后续操作调用相同的变量

Secondly I would want to know how to store the above string in a variable so that I could call the same variable for subsequent operations

我运行了以下命令,但没有任何输出。

I ran the following, but I am not getting any output.

curl --noproxy 10.23.193.1 -X POST http://10.23.193.1:80/rest/v3/login-sessions -d '{"userName":"admin", "password":"password"}' | grep -`E ""cookie":"


推荐答案

避免使用grep或sed这样的简单工具来解析JSON,因为它们无法正确处理引号或多行数据。最好使用支持JSON的程序,例如 jq

Avoid using simple tools like grep or sed to parse JSON as they won't handle things like quotes or multi-line data correctly. It's best to use a JSON-aware program such as jq.

使用jq既简单又强大:

With jq it's simple and robust:

curl ... | jq '.cookie'

要将Cookie存储在变量中,请使用- r 标志可让JQ打印出未加引号的原始字符串。

To store the cookie in a variable use the -r flag to have JQ print out the raw, unquoted string.

cookie=$(curl ... | jq -r '.cookie')

进一步阅读:

  • jq Manual
  • Parsing JSON with Unix tools
  • How to parse JSON with shell scripting in Linux?

这篇关于如何打印JSON字符串的一部分并将其存储在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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