0

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
1
  • You may want to show the error trace. How to Ask Commented Jun 18, 2015 at 23:49

2 Answers 2

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"]))
answered Jun 26, 2019 at 0:31
Sign up to request clarification or add additional context in comments.

Comments

0

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
answered Jun 18, 2015 at 23:49

1 Comment

Yes it is, but this doesn't make a difference; same error at same place. Good catch though

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.