D
D
Deeexz2021-12-08 05:49:58
Python
Deeexz, 2021-12-08 05:49:58

How to not output json in api, empty fields?

When displaying all variables, the result is:

Region: Moscow and Moscow region
Country: Russia
Operator: OOO "Skartel"

But if some parameter is empty, then the result is:

Region:
Country: Sweden
Operator:

It is necessary that only non-empty variables be displayed:

Country: Sweden

How can I do that?

import requests

country_region_operator = requests.get(f"https://fincalculator.ru/api/tel/46729047511")
cro_data = country_region_operator.json()

region = cro_data["region"]
country = cro_data["country"]
operator = cro_data["operator"]

print(f'Регион: {region}\nСтрана: {country}\nОператор: {operator}')

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergo Zar, 2021-12-08
@Sergomen

text  = f""
if region:
    text += f'Регион: {region}\n'
if country:
    text += f'Страна: {country}\n'
if operator:
    text += f'Оператор: {operator}'
print(text)

A
Antonio Solo, 2021-12-08
@solotony

import json
x = { 'Регион': '', 'Страна': 'Буркина-Фасо', 'Оператор': ''}
print(json.dumps({_:x[_] for _ in x if x[_]}, ensure_ascii=False))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question