nam pham
nam pham

Reputation: 21

Set default value for dict from json.loads

I want to add default value for key not exist in json.loads

I have a list of keys like this

["id", "name", "wkt", "created", "radius", "round"]

and many line json file which doesn't have enough keys like this:

{"id":"1", "name":"a", "round":5}   
{"id":"2", "wkt": "POINT(1.1)", "created":"2018-22-11T10:00:00"}   
{"id":"3", "radius":3}  

Expect result:

{"id":"1", "name": "a", "wkt":null, "created":null, "radius":null, "round":5}  

My current sollution

for line in lines:
    line_dict = json.loads(line)
    for key in keys:
        if not key in line_dict:
            line_dict[key] = None
    yield line_dict

Expect result

I want to find more efficient way to set default for not exist keys with json.loads. With object_hooks or object_pair_hook i had no success so far.

Upvotes: 2

Views: 7517

Answers (2)

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72755

I might be misunderstanding your question, but can you not do something like this?

def filler(d):
   for i in ["id", "name", "wkt", "created", "radius", "round"]:
     if i not in d:
       d[i] = None
   return d

json.loads('{"id":"1", "name":"a", "round":5}', object_hook=filler)

For me, this returns

{u'name': u'a', 'created': None, u'id': u'1', 'radius': None, 'wkt': None, u'round': 5}

Upvotes: 0

cs95
cs95

Reputation: 402533

You can initialise a dictionary of empty values and update accordingly.

keys = ["id", "name", "wkt", "created", "radius", "round"]       
default = dict.fromkeys(keys, None)

def read_json(filename):
    with open(filename, 'r') as f: 
        for line in f:
            d = default.copy()
            d.update(json.loads(line))
            yield d

Upvotes: 2

Related Questions