2015-11-30 31 views
1

以下是我从url收到的作为响应的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_srcipv4_dst我必须把它作为输入

我该怎么做?

回答

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 ; 

以上是伪代码基于ipv4_srcipv4_dstbyteCount找到。请注意,这两个属性在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" 
    } 
} 
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分别比d输入是在名为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 ... | jq -c --arg src 10.0.0.10 --arg dst 10.0.0.12 -f extract.jq 
相关问题