-2

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

Butcho
  • 3
  • 1
  • If you have a list of dictionaries, you can iterate over the list and either use `del d["subnetmask"]` or `d.pop("subnetmask")` (assuming your dict is `d` and you want to delete `subnetmask`). – Gugu72 Jul 08 '22 at 19:26
  • 2
    Welcome back to Stack Overflow! As a refresher, please take the [tour] and read [ask]. What have you already tried, and what do you need help with exactly? Like, to start, do you know [how to parse a JSON string](/questions/7771011/how-to-parse-data-in-json-format) and how to delete keys from a dict (or how to select keys)? – wjandrea Jul 08 '22 at 19:31

3 Answers3

2

You can use dict comprehension:

json_input = '''
[
  
  {
    "hostname": "bla",
    "ipaddress": "192.168.1.10",
    "subnetmask": "255.255.255.0",
    "iloip": "192.168.1.11"
   }
]
'''
desired_keys = {'hostname', 'ipaddress'}

json_filtered = json.dumps([{ k:v for (k,v) in d.items() if k in desired_keys} 
        for d in json.loads(json_input)])

print(json_filtered)

output:

'[{"hostname": "bla", "ipaddress": "192.168.1.10"}]'
SomeDude
  • 13,876
  • 5
  • 21
  • 44
0

I belive what you want to achieve can be done with the code given below:

import json

data_json = '{"hostname": "bla","ipaddress": "192.168.1.10","subnetmask": "255.255.255.0","iloip": "192.168.1.11"}'

data = json.loads(data_json)

chosen_fields = ['hostname', 'ipaddress']

for field in chosen_fields:
    print(f'{field}: {data[field]}')

Output:

hostname: bla
ipaddress: 192.168.1.10

Here what we do is we parse the stringified version of the json using the python's json module (i.e. json.loads(...)). Next decide on the fields we want to access (i.e. chosen_fields). Finally we iterate through the field we want to reach and get the corresponding values of the fields. This leaves the original json unmodified as you wished. Hope this helps.


Or else if you want these fields as a reduced json object:

import json

data_json = '{"hostname": "bla","ipaddress": "192.168.1.10","subnetmask": "255.255.255.0","iloip": "192.168.1.11"}'

data = json.loads(data_json)

chosen_fields = ['hostname', 'ipaddress']

reduced_json = "{" 
for field in chosen_fields:
    reduced_json += f'"{field}": "{data[field]}", '

reduced_json = list(reduced_json)
reduced_json[-2] = "}" 
reduced_json = "".join(reduced_json)
reduced = json.loads(reduced_json)

for field in chosen_fields:
    print(f'"{field}": "{reduced[field]}"')

Output:

"hostname": "bla"
"ipaddress": "192.168.1.10"

cangozpi
  • 89
  • 1
  • 6
-1

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

QwertYou
  • 333
  • 2
  • 12
  • I only need to show certain fields. Needs to return valid json – Butcho Jul 08 '22 at 19:33
  • @Butcho, see now – QwertYou Jul 08 '22 at 19:38
  • 1
    @QwertYou Yup, definitely! You could improve it further if you wanted by [not repeating yourself](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) about the keys -- instead factoring them out into a list, like `desired_keys = ["hostname", "ipaddress"]` ... `[{k: x[k] for k in desired_keys} for x in response]`. – wjandrea Jul 08 '22 at 19:52
  • Added this too, thanks for the comment on the code! In addition, now the code has become flexible, and if you need to add some field for "view" or remove it, then it's much easier now – QwertYou Jul 08 '22 at 19:58
  • 1
    Thanks to you both – Butcho Jul 08 '22 at 20:06
  • Quick question: response is already a json array, when I insert it into json.dumps, and then call jsonify, it's adding an additional double quotes around it and its refusing to pretty print. How would I fix that? – Butcho Jul 08 '22 at 20:19
  • now it is the same as I wrote :) – SomeDude Jul 08 '22 at 20:22
  • @Butcho, you already have a valid JSON, you don't need to use `json.dumps` – QwertYou Jul 09 '22 at 14:30