简体   繁体   English

我可以将字符串变量而不是文件传递给 jq 吗?

[英]Can I pass a string variable to jq not the file?

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).我想将 JSON 字符串转换为 bash 中的数组。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

I would suggest using a bash here string . 我建议在这里使用bash 字符串 eg 例如

jq '.key' <<< "$json_data"

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

For example: 例如:

 jq -n --argjson data "$json_data" '$data.key'

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 invalid as 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"

Use the bash: echo "$json_data" | jq '.key' 使用bash: echo "$json_data" | jq '.key' echo "$json_data" | jq '.key'

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)运行它。

#! /bin/bash
json_data='{"key":"value"}'
echo $json_data | jq --raw-output '.key'

If you're trying to do this in a .sh file, this is what worked for me: 如果您尝试在.sh文件中执行此操作,那么这对我.sh

local json_data $(getJiraIssue "$1")               # store JSON in var
echo `jq -n "$json_data" | jq '.fields.summary'`   # pass that JSON var to jq

如果要使用内联命令,我在Mac上发现了此功能:

echo '{"key":"value"}' | jq .key

Just do做就是了

$ jq '.key' <<< $'{"key":"value"}'
"value"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM