从JSON中仅为特定流提取一个字段

时间:2015-11-30 11:43:57

标签: json

以下是我收到的来自网址的响应的Json。

{"flows":[{"version":"OF_13","cookie":"0","tableId":"0x0","packetCount":"24","byteCount":"4563","durationSeconds":"5747","priority":"0","idleTimeoutSec":"0","hardTimeoutSec":"0","flags":"0","match":{},"instructions":{"instruction_apply_actions":{"actions":"output=controller"}}},

{"version":"OF_13","cookie":"45036000240104713","tableId":"0x0","packetCount":"0","byteCount":"0","durationSeconds":"29","priority":"6","idleTimeoutSec":"0","hardTimeoutSec":"0","flags":"1","match":{"eth_type":"0x0x800","ipv4_src":"10.0.0.10","ipv4_dst":"10.0.0.12"},"instructions":{"none":"drop"}},

{"version":"OF_13","cookie":"45036000240104714","tableId":"0x0","packetCount":"0","byteCount":"0","durationSeconds":"3","priority":"7","idleTimeoutSec":"0","hardTimeoutSec":"0","flags":"1","match":{"eth_type":"0x0x800","ipv4_src":"10.0.0.10","ipv4_dst":"127.0.0.1"},"instructions":{"none":"drop"}},

{"version":"OF_13","cookie":"0","tableId":"0x1","packetCount":"0","byteCount":"0","durationSeconds":"5747","priority":"0","idleTimeoutSec":"0","hardTimeoutSec":"0","flags":"0","match":{},"instructions":{"instruction_apply_actions":{"actions":"output=controller"}}}]}

所以,我有四个流程,我想只提取字段" byteCount "对于 ipv4_src ipv4_dst 标识的特定流程,我必须将其作为输入

我该怎么做?

2 个答案:

答案 0 :(得分:1)

json_array := JSON.parse(json_string)
foreach (element in json_array.flows):
    if(element.match.hasProperty('ipv4_src') && element.match.hasProperty('ipv4_dst')):
        if(element.match.ipv4_src == myValue && element.match.ipv4_dst == otherValue):
            print element.byteCount ;

以上是基于byteCountipv4_src查找ipv4_dst的伪代码。请注意,这两个属性在match属性中,可能包含也可能不包含它们。因此,首先检查它们的存在然后进行处理。

注意:格式化属性时,数组中的每个元素都是

{  
     "version":"OF_13",
     "cookie":"45036000240104713",
     "tableId":"0x0",
     "packetCount":"0",
     "byteCount":"0",
     "durationSeconds":"29",
     "priority":"6",
     "idleTimeoutSec":"0",
     "hardTimeoutSec":"0",
     "flags":"1",
     "match":{  
        "eth_type":"0x0x800",
        "ipv4_src":"10.0.0.10",
        "ipv4_dst":"10.0.0.12"
     },
     "instructions":{  
        "none":"drop"
     }
}

答案 1 :(得分:0)

以下是使用命令行工具jq执行选择和提取任务的方法:

首先用这三行创建一个文件,说" extract.jq":

.flows[]
| select(.match.ipv4_src == $src and .match.ipv4_dst == $dst)
| [$src, $dst, .byteCount]

接下来,假设所需的src和dst分别为10.0.0.10和10.0.0.12,并且输入位于名为input.json的文件中,请运行以下命令:

jq -c --arg src 10.0.0.10 --arg dst 10.0.0.12 -f extract.jq input.json

这会在每场比赛中产生一条线;就你的例子而言,它会产生:

["10.0.0.10","10.0.0.12","0"]

如果JSON来自某个命令(例如curl),您可以使用以下行中的管道:

curl ... | jq -c --arg src 10.0.0.10 --arg dst 10.0.0.12 -f extract.jq
相关问题