json 我可以将字符串变量传递给 jq 而不是文件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47105490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I pass a string variable to jq not the file?
提问by Maciek Rek
I want to convert JSON string into an array in bash. The JSON string is passed to the bash script as an argument (it doesn't exist in a file).
我想在 bash 中将 JSON 字符串转换为数组。JSON 字符串作为参数传递给 bash 脚本(它不存在于文件中)。
Is there a way of achieving it without using some temp files?
有没有办法在不使用一些临时文件的情况下实现它?
Similarly to this:
与此类似:
script.sh
#! /bin/bash
json_data='{"key":"value"}'
jq '.key' $json_data
jq: error: Could not open file {key:value}: No such file or directory
回答by jq170727
回答by peak
The value of the variable "json_data" that was given in the original question was not valid JSON, so this response still covers both cases (nearly-valid and valid JSON).
原始问题中给出的变量“json_data”的值不是有效的 JSON,因此此响应仍然涵盖这两种情况(几乎有效和有效的 JSON)。
Valid JSON
有效的 JSON
If "$json_data" does hold a valid JSON value, then here are two alternatives not mentioned elsewhere on this page.
如果“$json_data”确实包含有效的 JSON 值,那么这里有两个本页其他地方未提及的替代方法。
--argjson
--argjson
For example:
例如:
jq -n --argjson data "$json_data" '$data.key'
env
env
If the shell variable is not aleady an environment variable:
如果 shell 变量不是环境变量:
json_data="$json_data" jq -n 'env.json_data | fromjson.key'
Nearly-valid JSON
几乎有效的 JSON
If indeed $json_data is invalidas JSON but valid as a jq expression, then you could adopt the tactic illustrated by the following transcript:
如果 $json_data 确实作为 JSON无效但作为 jq 表达式有效,那么您可以采用以下脚本所示的策略:
$ json_data='{key:"value"}'
$ jq -n "$json_data" | jq .key
"value"
回答by Javier
Use the bash: echo "$json_data" | jq '.key'
使用 bash: echo "$json_data" | jq '.key'
回答by Ignacio Vazquez-Abrams
Absolutely. Just tell bash to give it a file instead.
绝对地。只需告诉 bash给它一个文件。
jq '.key' <(echo "$json_data")
And make sure you run it in bash, not sh.
并确保你在 bash 中运行它,而不是 sh。
回答by Supun Madushanka
#! /bin/bash
json_data='{"key":"value"}'
echo $json_data | jq --raw-output '.key'
回答by Abigail Nguyen
If you want to use inline command, I found this work on my Mac:
如果你想使用内联命令,我在我的 Mac 上找到了这个工作:
echo '{"key":"value"}' | jq .key
回答by Wesley Smith
If you're trying to do this in a .shfile, this is what worked for me:
如果您尝试在.sh文件中执行此操作,这对我有用:
local json_data $(getJiraIssue "") # store JSON in var
echo `jq -n "$json_data" | jq '.fields.summary'` # pass that JSON var to jq

