由于它是 JSON,因此应使用 JSON 感知工具来处理它。例如,如果您更喜欢 awk,可以使用 GNU awk 的 JSON 扩展。这是一个小操作方法。
首先下载并编译适当版本的 GNU awk、Gawkextlib 和gawk-json http://gawkextlib.sourceforge.net/json/json.html。其实这很简单,只需./configure
and make
。然后,编写一些代码:
awk '
@load "json" # enable json extension
{
lines=lines $0 # read json file records and buffer to var lines
if(json_fromJSON(lines,data)==1) { # once the json is complete
for(i in data["info"]["version"]) # that seems to be an array so all elements
print data["info"]["version"][i] # are outputed
lines="" # once done with the first json object
} # reset the var for more lines
}' file
这次输出:
2034.2
多解释一下:
JSON 文件结构可以从一行到多行不等,例如:
{"version":"4.9.123M","info":{"version":[2034.2],"description":""},"status":"OK"}
or:
{
"version": "4.9.123M",
"info": {
"version": [
2034.2
],
"description": ""
},
"status": "OK"
}
所以我们需要缓冲 JSON 行lines=lines $0
直到变量中有一个完整的有效对象lines
。我们使用扩展函数json_fromJSON()
以确定有效性if(json_fromJSON(lines,data)==1)
。验证时,对象被解开并存储到数组中data
。对于这个特定对象,数组的结构是:
data["version"]="4.9.123M"
data["info"]["version"][1]="2034.2"
data["info"]["description"]=""
data["status"]="OK"
我们可以使用这个递归数组扫描函数检查对象并产生它的一些输出:
awk '
@load "json"
function scan(a,p, q) { # a is array, p path to it, q is qnd *
if(isarray(a))
for(i in a) {
q=p (p==""?"":"->") i
scan(a[i],q)
}
else
print p ":" a
}
{
lines=lines $0
if(json_fromJSON(lines,data)==1)
scan(data) #
}' file.json
Output:
status:OK
version:4.9.123M
info->version->1:2034.2
info->description:
*)又快又脏
以下是如何从数组输出 JSON 的简短示例:https://stackoverflow.com/a/58109715/4162356 https://stackoverflow.com/a/58109715/4162356