I am trying to parse the below JSON, and extract name and interval from the elements.
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
...
I've tried the following:
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)
However, I always get an error that TypeError: string indices must be integers
What am I doing incorrectly? In the code, interfaces is a JSON acquired by doing json.load()
asked Jun 18, 2015 at 23:45
user3249763
1274 silver badges15 bronze badges
-
You may want to show the error trace. How to Askboardrider– boardrider2015年06月18日 23:49:24 +00:00Commented Jun 18, 2015 at 23:49
2 Answers 2
The "interface" and "rates" dictionary values are lists, so you need to index into them.
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"]))
Sign up to request clarification or add additional context in comments.
Comments
Isn't is supposed to be interface instead of statistic ??
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
1 Comment
user3249763
Yes it is, but this doesn't make a difference; same error at same place. Good catch though
lang-py