Friday, May 17, 2024
HomeCyber SecurityTypeError: record indices have to be integers or slices, not str |...

TypeError: record indices have to be integers or slices, not str | by Teri Radichel | Bugs That Chew | Jul, 2022


Issues iterating via and accessing JSON parts with Python

When you get this error whereas making an attempt to entry information in a JSON object verify to see whether or not you are attempting to entry an inventory or a dict (dictionary).

Python lists appear to be this:

mylist = [“apple”, “banana”, “cherry”]

Python record:

A python dict seems to be like this:

automobile = {
"model": "Ford",
"mannequin": "Mustang",
"12 months": "1964"
}

When you’ve got a json object like this with an inventory of automobiles and the attributes of every automobile are saved as a dict:

automobiles:
[{
"brand": "Ford",
"model": "Mustang",
"year": "1964"
},
{
"brand": "Jeep",
"model": "Gladiator",
"year": "2022"
}
]

In case you are accessing an inventory, loop via the objects within the record:

for merchandise in json:
#do one thing

When you’ve got a dict you’ll be able to entry the attribute you need utilizing brackets:

merchandise['name']

When you get the error:

TypeError: record indices have to be integers or slices, not str

then you might be in all probability making an attempt to entry a component in a dict, however first you must iterate via your record.

So as an alternative of this:

automobiles.model

Do that:

for automobile in automobiles:
print (automobile['Brand'])

Teri Radichel

When you appreciated this story please clap and comply with:

Medium: Teri Radichel or E-mail Checklist: Teri Radichel
Twitter: @teriradichel or @2ndSightLab
Requests providers by way of LinkedIn: Teri Radichel or IANS Analysis

© 2nd Sight Lab 2022

____________________________________________

Writer:

Cybersecurity for Executives within the Age of Cloud on Amazon

Want Cloud Safety Coaching? 2nd Sight Lab Cloud Safety Coaching

Is your cloud safe? Rent 2nd Sight Lab for a penetration take a look at or safety evaluation.

Have a Cybersecurity or Cloud Safety Query? Ask Teri Radichel by scheduling a name with IANS Analysis.

Cybersecurity & Cloud Safety Sources by Teri Radichel: Cybersecurity and Cloud safety courses, articles, white papers, shows, and podcasts



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments