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

Remove fields from a json array in Python

Currently I have a function returning json via jsonify.

[
  {
    "hostname": "bla",
    "ipaddress": "192.168.1.10",
    "subnetmask": "255.255.255.0",
    "iloip": "192.168.1.11"
   }
]
     

I want to keep it in json format, but I want to only show the fields I choose (i.e. reduce it). For this example, I want hostname and ipaddress.

Thanks

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

>Solution :

If I understand you correctly:

import json


response = [
    {
        "hostname": "bla",
        "ipaddress": "192.168.1.10",
        "subnetmask": "255.255.255.0",
        "iloip": "192.168.1.11",
    }
]
desired_keys = ["hostname", "ipaddress"]
new_response = json.dumps(
    [{key: x[key] for key in desired_keys} for x in response]
)

And now you have a new_response – valid JSON, with which you can continue to work on

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