“无效的数字文字" jq尝试使用变量修改JSON时发生错误 [英] "Invalid numeric literal" error from jq trying to modify JSON with variable
问题描述
我想将值传递到bash脚本中,该脚本将使用jq更改json文件中的值.我已经为此工作了一段时间,无法克服第一组错误.
I am wanting to pipe values into a bash script that will change values in a json file using jq. I've been working on this for a while now and I can't get past the first set of errors.
这是我简单的json文件:
Here is my simple json file:
{
"0000000": {
"pogo": "AJHVUYKJBOIHKNNLNM"
},
"7000000": {
"pogo": "PPPVUYKJBOIHKNNLNM"
}
}
这是我的脚本
#!/bin/bash
#-- pass into script
pgid="${1}"
tpogo="${2}"
file="file.json"
#-- tmp files
tmp_dir="$(mktemp -d -t 'text.XXXXX' || mktemp -d 2>/dev/null)"
tmp_input1="${tmp_dir}/temp_input1.txt"
if [ ! -n "$2" ]; then
{ echo "Check your command as you are missing a variable ..."; echo "Example: script.sh "00000001" "jvkkjbkjbd" ..."; }
exit 1;
fi
jq -r ".${pgid}.pogo = \"${tpogo}\"" "$file" > "$tmp_input1"
cat "$tmp_input1"
rm -rf "$tmp_dir"
以下是错误:
jq: error: Invalid numeric literal at EOF at line 1, column 9 (while parsing '.0000000.') at <top-level>, line 1:
.0000000.pogo = "XXXXXXX"
jq: error: syntax error, unexpected IDENT, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.0000000.pogo = "XXXXXXX"
jq: 2 compile errors
我从堆栈中尝试了许多变体,其中大多数看起来与我现在正在做的事情相似.
I have tried so many variations from stack and most of them look similar to what I am doing now.
推荐答案
至于当前的问题:.key
与{ "foo": "value" }
一起使用,但是.100
与{ "100": "value" }
一起使用;您所依赖的语法是糖,仅适用于键的有限子集. .["100"]
可以工作,但是通过将shell变量扩展为在代码中解析的字符串来生成它是脆弱的(jq
在当前版本中不是副作用,但是在 do 支持的语言中I/O操作,这样的替代可以用于注入攻击.要以正确的方式执行操作,请将代码中的变量带外传递,并以不依赖于变量内容的方式将其用于查找.
As for the immediate issue: .key
works with { "foo": "value" }
, but .100
doesn't work with { "100": "value" }
; the syntax you're relying is sugar, only available for a limited subset of keys. .["100"]
would work, but generating that by expanding shell variables into strings parsed as code is fragile (jq
isn't a side-effecting language as of current releases, but in languages that do support I/O operations, such substitutions can be leveraged for injection attacks). To do things the Right Way, pass your variables out-of-band from your code, and use them for lookups in a manner that doesn't rely on what they contain.
与awk的-v var="$value"
等效的jq
是--arg var "$value"
,因此被使用:
The jq
equivalent to awk's -v var="$value"
is --arg var "$value"
, used thusly:
jq --arg pgid "$pgid" \
--arg tpogo "$tpogo" \
'.[$pgid].pogo = $tpogo'
使用您的数据进行测试:
Testing this with your data:
json='{"0000000":{"pogo":"AJHVUYKJBOIHKNNLNM"},"7000000":{"pogo":"PPPVUYKJBOIHKNNLNM"}}'
pgid="0000000"
tpogo="XXXXXXX"
jq --arg pgid "$pgid" --arg tpogo "$tpogo" \
'.[$pgid].pogo = $tpogo' <<<"$json"
...作为输出发出:
...emits as output:
{
"0000000": {
"pogo": "XXXXXXX"
},
"7000000": {
"pogo": "PPPVUYKJBOIHKNNLNM"
}
}
这篇关于“无效的数字文字" jq尝试使用变量修改JSON时发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!