解析Python JSON

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (3)

我试图解析下面的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)

但是,我总是得到一个错误,TypeError:字符串索引必须是整数

我做错了什么?在代码中,接口是通过执行json.load()获取的JSON

提问于
用户回答回答于

是不是应该是界面而不是统计?

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
用户回答回答于
print("name = {}".format(reply["interface"][0]["name"]))
rates = reply["interface"][0]["rate"]
for rates_index in range(len(rates)):
    print("rate = {}".format(rates[rates_index]["interval"]))

扫码关注云+社区

领取腾讯云代金券