0

I have a JSON file that looks like the following (not the whole file)

"route-information" : [
{
    "attributes" : {"xmlns" : "http://xml.juniper.net"}, 
    "route-table" : [
    {
        "comment" : "keepalive", 
        "table-name" : [
        {
            "data" : "inet"
        }
        ], 
        "destination-count" : [
        {
            "data" : "24324"
        }
        ], 
        "total-route-count" : [
        {
            "data" : "47432"
        }
        ], 
        "active-route-count" : [
        {
            "data" : "43252"
        }
        ], 
        "holddown-route-count" : [
        {
            "data" : "0"
        }
        ], 
        "hidden-route-count" : [
        {
            "data" : "1"
        }
        ],

I am trying to access the 'comment' part by using python. So far I have this:

import json

# read file
with open('route-table.json') as file:
    data = json.load(file)

print(data["route-information"]["route-table"]["comment"])

Whenever I run this part I get the following error and I can't seem to fix it.

Traceback (most recent call last):
File "json_test.py", line 7, in <module>
print(data["route-information"]["route-table"]["comment"])
TypeError: list indices must be integers or slices, not str
Kaiser
  • 15
  • 1
  • 5
  • Does this answer your question? [Reading JSON from a file?](https://stackoverflow.com/questions/20199126/reading-json-from-a-file) – Innat Oct 27 '20 at 14:39

2 Answers2

2

data["route-information"] is a list, so you can do data["route-information"][0] to access the dict inside, same with data["route-information"][0]["route-table"]:

print(data["route-information"][0]["route-table"][0]["comment"])

If you intend to use data later and are okay with changing it's structure, you can replace the lists with their first elements (assuming they only have one element) so that you won't have to use the [0] notation every time you need to access the dicts:

data["route-information"] = data["route-information"][0]
data["route-information"]["route-table"] = data["route-information"]["route-table"][0]

print(data["route-information"]["route-table"]["comment"])
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

MrGeek is correct. Just to add more info

  • [] are for JSON arrays, which are called list in Python
  • {} are for JSON objects, which are called dict in Python

To get the value we do as follows:

data["route-information"][0]["route-table"][0]["comment"]
data["attributes"]["xmlns"]
Innat
  • 16,113
  • 6
  • 53
  • 101