我有一个 JSON 格式的 Web 服务器响应的输出,如下所示:
{"status":"OK","result":{"string":{"variable":0},"string2":[{"id":"03489579q2074hvissdiuh:023427598042ztuoihsgasflbkc6dc7e000af669d6c94857d1a28f8cb338a9691c80eb8857c750c8ead70f29a","string3":"string4","latitude":"01.XXXXXXXX","longitude":"02.XXXXXXX"},]}}
并保存为response.txt
.它会重复多次迭代,因此之后"02.XXXXXXX"}
是","
我的预期输出只是以下内容"id"
:
03489579q2074hvidssiuh:023427598042ztuoihsgasflbkc6dc7e000af669d6c94857d1a28f8cb338a9691c80eb8857c750c8ead70f29a
每个 id 后面换一个新行。
我尝试过诸如
grep -o '".*"' somefile | tr -d '",{}[]'
awk -F- '{
for (i=1;i<=NF;i++) {
if ($i ~ "^ram.+") { sub("^ram","",$i); print $i} }
}' response.txt
id
sed 's/.*id\(\w\+\).*/\1/' response.txt
sed 's/.*id..\(.*\)..300.*/\1/' -d '",{}[]' response.txt
sed 's/^.* id (\([0-9\.%]*\).*$/\1/' response.txt
但它要么返回所有内容,仅返回一些特殊字符仍然存在的第一次迭代,要么返回错误,因为默认情况下 awk 在 macOS 终端中不可用。
谢谢
编辑:这是具有更多迭代的输出
{"status":"OK","result":{"string1":{"veriable":0},"string2":[{"id":"XXXXX:XXXXX","tier":"normal","latitude":"01.XXXXX","longitude":"02.XXXXX"},{"id":"XXXXX:XXXXX","tier":"normal","latitude":"01.XXXXX","longitude":"02.XXXXX"},{"id":"XXXXX:XXXXX,"tier":"special","latitude":"01.XXXXX","longitude":"02.XXXXX"},{"id":"XXXXX:XXXXX","tier":"normal","latitude":"01.XXXXX","longitude":"02.XXXXX"}]}}
答案1
使用jq
:
jq -r '.result.string2[].id' response.txt
输入:
{
"status": "OK",
"result": {
"string1": {
"veriable": 0
},
"string2": [
{
"id": "XXXXX:XXXXX",
"tier": "normal",
"latitude": "01.XXXXX",
"longitude": "02.XXXXX"
},
{
"id": "XXXXX:XXXXX",
"tier": "normal",
"latitude": "01.XXXXX",
"longitude": "02.XXXXX"
},
{
"id": "XXXXX:XXXXX",
"tier": "special",
"latitude": "01.XXXXX",
"longitude": "02.XXXXX"
},
{
"id": "XXXXX:XXXXX",
"tier": "normal",
"latitude": "01.XXXXX",
"longitude": "02.XXXXX"
}
]
}
}
输出:
XXXXX:XXXXX
XXXXX:XXXXX
XXXXX:XXXXX
XXXXX:XXXXX