0

Suppose I have a json like str and it has mixture of key and dict. I want to set a default value if target key is not existed. I can use get method or try and catch block but it does not look nice. Any better solution? Thanks for your time.

import json
j_str = '''{
   "key1":[
      {
         "val1":1,
         "key2":2
      }
   ]
}'''
j_dict = json.loads(j_str)

print(j_dict['key1'][0]['val1'])
  • The best way would be to have a default dictionary structure and update that with the new json data. I answered a question like that [here](https://stackoverflow.com/questions/66383920/merge-deep-json-files-in-python), but also [this](https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-taking-union-of-dictiona/26853961#26853961) post looks into merging dictionaries. Otherwise you can use `.get(val, default)`, or the `try/except` approach, because these are valid solutions. – Thymen Mar 05 '21 at 10:38
  • It could have list or not, so very dynamic situation. Something like get may helpful but I don't know how to handle the list with get. Thanks for giving some pointer! – Abdullah Raihan Bhuiyan Mar 05 '21 at 15:53
  • The first solution I provided ([this one](https://stackoverflow.com/questions/66383920/merge-deep-json-files-in-python)) can handle `dict`, `list` and some nesting in them, with a constraint on `lists` items (the inserting `list` need to have the same number of elements, otherwise it is impossible to determine the overlap position). The only thing I could find for default values for `lists` is [this](https://stackoverflow.com/questions/5125619/why-doesnt-list-have-safe-get-method-like-dictionary) post. – Thymen Mar 05 '21 at 18:11
  • Your answer is a valid approach to solve the issue. I appreciate your help. I will try to implement this on my project and will write the details later. Thanks! – Abdullah Raihan Bhuiyan Mar 08 '21 at 12:25
  • This lib sounds interesting! https://github.com/jmespath/jmespath.py – Abdullah Raihan Bhuiyan Mar 09 '21 at 13:01

0 Answers0