我正在尝试使用sed来转换这个json:
{
"terraform_version": "0.14.8",
"terraform_revision": "",
"provider_selections": {
"registry.terraform.io/hashicorp/azuread": "1.3.0",
"registry.terraform.io/hashicorp/azurerm": "2.47.0",
"registry.terraform.io/hashicorp/cloudinit": "2.1.0",
"registry.terraform.io/hashicorp/external": "2.0.0",
"registry.terraform.io/hashicorp/kubernetes": "2.0.2",
"registry.terraform.io/hashicorp/local": "2.0.0",
"registry.terraform.io/hashicorp/null": "3.0.0",
"registry.terraform.io/hashicorp/template": "2.2.0",
"registry.terraform.io/hashicorp/tls": "3.0.0"
},
"terraform_outdated": false
}如下所示:
{
"terraform_version": "0.14.8",
"terraform_revision": "",
"provider_selections": "{\"registry.terraform.io/hashicorp/azuread\":\"1.3.0\",\"registry.terraform.io/hashicorp/azurerm\":\"2.47.0\",\"registry.terraform.io/hashicorp/cloudinit\":\"2.1.0\",\"registry.terraform.io/hashicorp/external\":\"2.0.0\",\"registry.terraform.io/hashicorp/kubernetes\":\"2.0.2\",\"registry.terraform.io/hashicorp/local\":\"2.0.0\",\"registry.terraform.io/hashicorp/null\":\"3.0.0\",\"registry.terraform.io/hashicorp/template\":\"2.2.0\",\"registry.terraform.io/hashicorp/tls\":\"3.0.0\"}",
"terraform_outdated": "false"
}从本质上讲,provider_selections应该封装在引号中,而其中的引号则进行转义。我还需要terraform_outdated值是一个字符串。
我尝试过这样做:
cat jsondata.json | sed 's/{/"{/2' | sed 's/}/"}/1'但我想不出其他的原因。
发布于 2021-03-19 06:39:42
如果你可以使用python:
#!/usr/bin/env bash
python -c "import json,sys
data=json.loads(open(sys.argv[1]).read())
data['provider_selections'] = json.dumps(data['provider_selections'])
print(json.dumps(data))
" data.json发布于 2021-03-19 20:04:07
使用sed,如下所示:
sed -r '/: \{/{x;N;:L;N;s/},/},/;TL;s/\"/\\\"/g;x;G;s/\n *//g};s/: ([^\"].*[^,])(,)?$/: \"\1\"\2/' file.json扩展到多行
sed -r '
/: \{/{
x
N
:L
N
s/},/},/
TL
s/\"/\\\"/g
x
G
s/\n *//g
}
s/: ([^\"].*[^,])(,)?$/: \"\1\"\2/
' file.json但是,像上面这样使用sed进行格式转换是不通用的……
发布于 2021-03-19 05:40:58
如果ed可接受/可用。
#!/usr/bin/env bash
ed -s file.json <<-'EOF'
g/: {/+1;/},/-1s/\"/\\\"/g
g/: {/+1;/},/-1s/[[:blank:]]*//
g/: {/+1;/},/s/[[:blank:]]\{1,\}//
g/: {/;/},/j
.,+s/\(.*\) \({\?.*}\?\)/\1 "\2"/
,p
Q
EOF如果输出正确,只需将Q更改为w即可就地编辑文件。
仅在GNU ed上测试。
https://stackoverflow.com/questions/66698016
复制相似问题