简体   繁体   中英

Select data from JSON file with Python

I have a JSON file with the dataset below:

[
    {
        "key": {
            "domain": "mail_1.com"
        },
        "data": {
            "array": [
                {
                    "area": "yey",
                    "number": "2000",
                    "Name": "Maria",
                    "Username": "Maria2",
                    "ID_nb": "11228169"

                }
            ]
        },
        "class": "1.1"
    },
    {
        "key": {
            "domain": "john.com"
        },
"data": {
            "array": [
                {
                    "area": "house",
                    "number": "4000",
                    "Name": "John",
                    "Username": "John22",
                    "ID_nb": "1124562"
                }
            ]
        },
        "class": "1.3"
    }

From this JSON file, I am trying to create a new JSON file with each key:domain and corresponding data:array:area and data:array:number It should give something like:

[
    {
        "key": {
            "domain": "mail_1.com"
        },
        "data": {
            "array": [
                {
                    "area": "yey",
                    "number": "2000"
                }
            ]
        },

    {
        "key": {
            "domain": "john.com"
        },
"data": {
            "array": [
                {
                    "area": "house",
                    "number": "4000",
                }
            ]
        }

Can you please help me? Thank you for your help!

Assuming you just want to remove "Name", "Username" and "ID_nb"

with open('path_to_your_file.json') as jf:
     js = json.load(jf)
     for elem in js:
         elem['data']['array'][0].pop('Name', None)
         elem['data']['array'][0].pop('Username', None)
         elem['data']['array'][0].pop('ID_nb', None)

The 'None' from pop is just to return nothing instead of exception if there is no element element with that name to pop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM