Home > Enterprise >  Include or exclude JSON data if the value is empty WITHOUT using multiple If statements
Include or exclude JSON data if the value is empty WITHOUT using multiple If statements

Time:06-17

I have this JSON to send via python requests. There are about 200 separate items. I want to set each item in the JSON to a variable and if the variable is empty I want to exclude the item from the list. How can I do this efficiently? I could put a ton of IF statements in, but I don't think that's very efficient.

#The variables:
_var1 = 123
_var2 = 40
_var3 = ""
_var4 = 5

#The JSON:
"""
{
  "id": _var1,
  "weight": _var2,
  "width": _var3,
  "depth": _var4
  }
"""

#My desired result:
"""
{
  "id": _var1,
  "weight": _var2,
  "depth": _var4
  }
"""

I assume I could could use multiple if/else statements. and then concatenate all of the strings.

if len(_var1)>0:
    print(str(_var11))
else: print("")
if len(_var2)>0:
    print(str(_var2))
else: print("")

I'm also assuming someone has a better way. I don't really want to write 200 if/else statements.

CodePudding user response:

You need a single if clause to check if it's empty

import json
keys = ["id", "weight", "width", "depth"]
vals = [_var1, _var2, _var3, _var4]

# check if a var is empty
d = {k:v for k,v in zip(keys, vals) if v}
j = json.dumps(d, indent=2)
print(j)


# {
#   "id": 123,
#   "weight": 40,
#   "depth": 5
# }

CodePudding user response:

Use a dictionary comprehension to loop through the dictionary, and create a new dictionary that only has the non-empty elements.

And use the json module to convert to/from JSON.

import json

old_dict = json.loads(old_json)
new_dict = {key: value for key, value in old_dict.items() if len(str(value)) > 0}
new_json = json.dumps(new_dict)
  • Related