Loading a normal json file. How do I find if this key exists in json string -> jsonstreng["kjoretoydataListe"][0]["kjennemerke"][1]["kjennemerke"]
Doing this of course without breaking my program if it's not.
CodePudding user response:
jsonstreng = {
"kjoretoydataListe":
[
{
"kjoretoyId": {"kjennemerke":"EK 17058","understellsnummer":"5YJXCCE29GF009633"},
"forstegangsregistrering": {"registrertForstegangNorgeDato":"2016-09-07"},
"kjennemerke": [
{"fomTidspunkt":"2016-09-07T00:00:00 02:00","kjennemerke":"EK 17058","kjennemerkekategori":"KJORETOY",
"kjennemerketype":{"kodeBeskrivelse":"Sorte tegn p- hvit bunn","kodeNavn":"Ordin-re kjennemerker","kodeVerdi":"ORDINART","tidligereKodeVerdi":[]}},{"fomTidspunkt":"2022-08-19T17:04:04.334 02:00","kjennemerke":"GTD","kjennemerkekategori":"PERSONLIG"}
]
}
]
}
def checkIfKeyExistsInDict(in_dict, i_key):
if(isinstance(in_dict, dict)):
if(i_key in in_dict):
print(i_key " found in: " str(in_dict))
print()
for j_key in in_dict:
checkIfKeyExistsInDict(in_dict[j_key], i_key)
elif(isinstance(in_dict, list)):
for j_key in range(len(in_dict)):
checkIfKeyExistsInDict(in_dict[j_key], i_key)
checkIfKeyExistsInDict(jsonstreng, "kjennemerke")
CodePudding user response:
If you are using Python, the way to find if key (let's say "kjennemerke") is present in a JSON object (let's say "jsonstreng") is:
if ("kjennemerke" in jsonstreng):
"""If body goes here"""
pass
Just for info, if you are trying to do the same in thing in JavaScript the if condition above will look like as shown below:
let jsonstreng_with_key = {
"kjennemerke": 1
}
let jsonstreng_without_key = {} // Empty object
if(jsonstreng_with_key.hasOwnProperty('kjennemerke')){
console.log("jsonstreng_with_key has key 'kjennemerke'");
} else {
console.log("jsonstreng_with_key does not have key 'kjennemerke'");
}
if(jsonstreng_without_key.hasOwnProperty("kjennemerke")){
console.log("jsonstreng_without_key has key 'kjennemerke'");
} else {
console.log("jsonstreng_without_key does not have key 'kjennemerke'");
}