2015-06-18 208 views
0

我想解析下面的JSON,並從元素中提取名稱和間隔。解析Python JSON

reply "[ { 
    "interface" : [ { 
    "name" : "ethernet39", 
    "number" : 39, 
    "rate" : [ { 
     "interval" : 45, 
     "rx-bad-vlan-rate" : 0, 
     "rx-broadcast-packet-rate" : 0, 
     "rx-byte-rate" : 0, 
     "rx-drop-rate" : 0, 
     "rx-error-rate" : 0, 
     "rx-multicast-packet-rate" : 0, 
     "rx-unicast-packet-rate" : 0, 
     "timestamp" : "2015-06-18T21:59:23.703Z", 
     "tx-broadcast-packet-rate" : 0, 
     "tx-byte-rate" : 0, 
     "tx-drop-rate" : 0, 
     "tx-error-rate" : 0, 
     "tx-multicast-packet-rate" : 0, 
     "tx-unicast-packet-rate" : 0 
    }, { 
     "interval" : 45, 
     "rx-bad-vlan-rate" : 0, 
     "rx-broadcast-packet-rate" : 0, 
     "rx-byte-rate" : 0, 
     "rx-drop-rate" : 0 
... 

我已經試過如下:

for x in range(0,len(interfaces)): 
    for interface in interfaces[x]: 
     entry = {} 
     entry['name'] = statistic['name'] 
     for interval in statistic['rate']: 
     entry['byte_rate'] = interval['rx-byte-rate'] 
     entry['packet_rate'] = interval['rx-unicast-packet-rate'] 
     entry['timestamp'] = interval['timestamp'] 
     entry['droprate'] = interval['rx-drop-rate'] 
     entry['errorrate'] = interval['rx-error-rate'] 
    entries.append(entry) 

不過,我總是得到一個錯誤, 類型錯誤:字符串索引必須是整數

我在做什麼錯誤?在代碼中,接口是通過執行json.load獲取的JSON()

+0

您可能想要顯示錯誤跟蹤。 [問] – boardrider

回答

0

是不是應該是接口而不是統計信息?

for x in range(0,len(interfaces)): 
    for interface in interfaces[x]: 
     entry = {} 
     entry['name'] = interface['name'] 
     for interval in interface['rate']: 
     entry['byte_rate'] = interval['rx-b 
+0

是的,但這沒有什麼區別;同一地點出現同樣的錯誤。雖然很好,但 – user3249763

+0

您是否已經解決了這個問題? – Vasif