How to put certain values of json files on the list with Python?

[
    [
        {
            "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

>Solution :

In your example, my_data is the whole json:


[
    [
        {
            "indexnum": 677,
            "type": 1,
            "user": 54846,
            "push": 0,
            
        },
        {
            
            "indexnum": 2321,
            "type": 1,
            "user": 77924,
            "push": 0,
            
        }
        
    ]
]

This is my_data[0]

[
    {
        "indexnum": 677,
        "type": 1,
        "user": 54846,
        "push": 0,
        
    },
    {
        
        "indexnum": 2321,
        "type": 1,
        "user": 77924,
        "push": 0,
        
    }
    
]

This is my_data[0][0]

{
    "indexnum": 677,
    "type": 1,
    "user": 54846,
    "push": 0,
    
}

This is my_data[0][0][‘indexnum’]

677

Leave a Reply