2017-09-28 1 views
0

1.jsonファイルには多くの盗聴WIFIパケットが含まれていますので、最初の "wlan"オブジェクトで見つかる受信機と送信機のMACアドレスを取得します。と "wlan.sa"。 data [0]は最初のWIFIパケットです。pythonを使ってjsonファイルで同じオブジェクトをマージする方法

Q1: しかし、jsonロード後にwlanの要素を表示しようとすると、2番目の "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ファイルで2つの 'WLAN' オブジェクトがあります。これら2つの 'wlan'オブジェクトの要素を、どのようにして1つの '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) 
関連する問題