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
1

2 Answers 2

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"])
Sign up to request clarification or add additional context in comments.

Comments

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"]

Comments

Your Answer

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.