2017-09-28 94 views
0

1.json文件包含很多嗅探WIFI數據包,我想要獲取可以在名爲「wlan.ra」的第一個「wlan」對象中找到的接收器和發送器的mac地址。和「wlan.sa」。數據[0]是第一個WIFI數據包。如何使用python合併json文件中的相同對象

Q1: 但是,當我嘗試打印json加載後的wlan元素時,它只顯示第二個「wlan」對象的元素,所以沒有「wlan.ra」和「wlan.sa」數據。

with open('1.json','r') as json_data: 
    data = json.load(json_data) 
a=data[0] 
print a 

Q2: 有我的JSON文件中的兩個 'WLAN' 的對象。我如何將這兩個「wlan」對象中的元素合併爲一個「wlan」對象?

以下是我的代碼,但它不工作:JSON文件的

with open('1.json','r') as f: 
    data=json.load(f) 
    for i in data: 
     i['_source']['layers']['wlan'].update() 

截圖:

Wlan obj - 1.json

回答

0
''' 
Created on 2017/10/3 

@author: DD 
''' 

import os 

def modify_jsonfile(jsonfile): 
''' 
replace wlan to wlan1/wlan2 
''' 
FILESUFFIX = '_new' # filename suffix 
LBRACKET = '{' # json object delimiter 
RBRACKET = '}' 
INTERSETED = '"wlan"' # string to be replaced 
nBrackets = 0 # stack to record object status 
nextIndex = 1 # next index of wlan 
with open(jsonfile, 'r') as fromJsonFile: 
    fields = os.path.splitext(jsonfile) # generate new filename 
    with open(fields[0] + FILESUFFIX + fields[1], 'w') as toJsonFile: 
     for line in fromJsonFile.readlines(): 
      for ch in line: # record bracket 
       if ch == LBRACKET: 
        nBrackets += 1 
       elif ch == RBRACKET: 
        nBrackets -= 1 
       if nBrackets == 0: 
        nextIndex = 1 
      if (nextIndex == 1 or nextIndex == 2) and line.strip().find(INTERSETED) == 0: # replace string 
       line = line.replace(INTERSETED, INTERSETED[:-1] + str(nextIndex) + INTERSETED[-1]) 
       nextIndex += 1 
      toJsonFile.write(line); 
print 'done.' 

if __name__ == '__main__': 
jsonfile = r'C:\Users\DD\Desktop\1.json'; 
modify_jsonfile(jsonfile) 
相關問題