I have this Json file, and I want to get the "navn" out with a iterating. I need it to print: Traktor Bil and nothing else, how do I do that ?
[
{"navn": "Traktor", "år": 10, "købspris": 10000},
{"navn": "Bil", "år": 20, "købspris": 100000},
{},
{}
]
So far I have this idea I know I need to import json file, and iterating through it but every time it gives me a error... I have tried searching the whole wide web and nothing came up my code so far:
import json
def main():
f = open("/Users/maltheschroderjakobsen/Desktop/coding/test/mat.json",)
f = json.load(f)
for key in f["navn"]:
print (key)
main()
But every time I try anything else it gives me a error
CodePudding user response:
f
seems to be a list, not a dictionary:
for dct in f:
if "navn" in dct: # the elements are dicts!
print(dct["navn"])
CodePudding user response:
It's because some dicts have no key navn
. Use dict.get
instead:
import json
def main():
file = open("/Users/maltheschroderjakobsen/Desktop/coding/test/mat.json",)
data = json.load(file)
for dct in data:
print(dct.get("navn", ""))
main()
CodePudding user response:
So long as the JSON only has dicts, you can do:
js='''\
[
{"navn": "Traktor", "år": 10, "købspris": 10000},
{"navn": "Bil", "år": 20, "købspris": 100000},
{},
{}
]'''
import json
>>> [e['navn'] for e in json.loads(js) if e.get('navn', '')]
['Traktor', 'Bil']
JSON can also have other datatypes such as lists or numeral. If there is a possibility of something other than a dict
in the JSON, you can do:
[e['navn'] for e in json.loads(js) if isinstance(e, dict) and e.get('navn', '')]