Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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,…])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading