在bash脚本中提取JSON值的更好方法 [英] A better way to extract JSON value in bash script
问题描述
有人能建议我从Json对中提取值的更好/更巧妙的方法吗?
Can anyone suggest a better / neater way to extract the value from a Json pair than what I've got so far below pls...
我的Json对是
{"myKeyName":"myKeyValueVariableLength"}
存储在myFile.txt中,我只想要KeyValue(不带引号).我目前所拥有的是:
is stored in myFile.txt and I just want the KeyValue (without quotes). What I've currently got is :
#!/bin/bash
PAIR=$(<myFile.txt)
IFS=': ' read -a arr <<< $PAIR
ONE="${arr[1]%?}"
TWO="${ONE%?}"
THREE=${TWO#'"'}
echo $THREE
这确实对我有用,但是我猜有更整齐的方法了吗?我听说过jsawk,但想尝试并尽可能在bash中做所有事情.
This does work for me but I'm guessing there is a much neater way ? I have heard of jsawk but would like to try and do all within bash if possible.
Tks
推荐答案
Bash包含一个内置的正则表达式测试,格式为[[ string =~ regex ]]
.运行后,捕获的子模式将存储在名为$BASH_REMATCH
Bash contains a built-in regex test, which takes the form [[ string =~ regex ]]
. After it's run, captured sub-patterns are stored in an array called $BASH_REMATCH
在处理引号和转义时有点麻烦/不可思议,所以我花了一些时间才能开始工作,但这似乎行得通:
It's a bit fussy / magic about handling quotes and escapes, so it took me a while to get working, but this seems to work:
PAIR='{"myKeyName":"myKeyValueVariableLength"}'
[[ $PAIR =~ ^\{\"([^\"]+)\":\"([^\"]+)\"\}$ ]] && echo "The key is ${BASH_REMATCH[1]} and the value is ${BASH_REMATCH[2]}"
[或者,以Unix方式执行,然后调用sed
,awk
,perl
,python
,php
或已安装的任何可简化生活的方法.类似于php -r "print_r( json_decode('"$PAIR"') );"
的内容...]
[Alternatively, do it The Unix Way, and invoke sed
, awk
, perl
, python
, php
, or whatever you have installed that will make your life easier. Something along the lines of php -r "print_r( json_decode('"$PAIR"') );"
for instance...]
这篇关于在bash脚本中提取JSON值的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!