[
[
{
"indexnum": 677,
"type": 1,
"user": 54846,
"push": 0,
},
{
"indexnum": 2321,
"type": 1,
"user": 77924,
"push": 0,
}
]
]
import json
with open('./79553/combined.json', 'r',encoding='UTF-8') as infile:
my_data = json.load(infile)
datalist1 = []
print(my_data['indexnum'])
That is my saved json file and I want to extract only indexnum from that file
and append them in a new list.
(ex. datalist1 = [677,2321,…])
Whether the file was read successfully, all items were outputted normally when I ‘print(datalist1)’.
but ‘print(my_data[‘indexnum’])’ has ‘list indices must be integers or slices, not str’ error occured.
How to solve them?
try:
I try my_data[0][‘indexnumber’]
same problem
4
Answers
In your example,
my_data
is the whole json:This is my_data[0]
This is my_data[0][0]
This is my_data[0][0][‘indexnum’]
Your JSON format is not uniformly equal bracketed. Either the bracketing is made uniform for the entire file or you access it with the correct list command. my_data[0][0]["indexnum"]
I would highly recommend to use {} brackets througout the whole file.
outputs [677, 2321].
But you need to remote trailing commas in lines like
"push": 0,
, because it is not valid JSON this wayYour json data is formatted as list nested in list
Therefore, to get the attribute "indexnum" of the items, you may want to use the double loop after reading the json data
If you make sure that the first inner list is the only list you have, use this
or the list comprehensive form