Rui
Rui

Reputation: 95

Python parsing Json - "X is None" doesn't catch empty objects

I am new to Python and I am trying to parse a Json file using Python. The Json file is a nested file. While I am trying to exact the "conversation_id" item, the list that contains this item, and the list above sometimes can be empty. I am hoping to replace empty list as string "N/A", otherwise grab the item. Code I am using is as following:

for log in data['logs']:
    print("Processing log "+log['log_id'])

    logcolumns=[]

    if log['request'] is None:
            logcolumns.append("N/A")
    elif log['request']['context'] is None:
           logcolumns.append("N/A")
    else:
        logcolumns.append(log['request']['context']['conversation_id'])
try:
        print("\t".join(logcolumns),file = conv_tsv)
    except KeyError:pass

del logcolumns

Traceback error I got is

Processing log cafa1077-f479-4c55-ac34-3bc3ebbb41fc
Traceback (most recent call last):
  File "conversation_log_2.py", line 43, in <module>
    logcolumns.append(log['request']['context']['conversation_id'])
KeyError: 'conversation_id'

The "request" list that is associated with this log id is shown as below in the json file:

{"request": {"input": {}, "context": {}},

A full request list would be like this:

{"request": {"input": {"text": "haha"}, "context": {"conversation_id": "328d2320-f488-4f46-b71f-6cdfb1b79106", "system": {"dialog_stack": [{"dialog_node_s": "root"}], "dialog_turn_counter": 1, "dialog_request_counter": 1, "_node_output_map_s": "{\"Welcome\":[0,1,0]}", "branch_exited_s": "true", "branch_exited_reason_s": "completed"}}}, 

When I went to the output file, which is conv.tsv, there is N/A in the output.

Upvotes: 0

Views: 937

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78554

You seem to have the syntax quite moodled up. Is the try/except supposed to be wrapping the if/elif? Do you actually want if/elifs?

Note that log['request'] is None does not test that the key's value is an empty dict.

You can use the .get method that returns a default when the key is not found:

logcolumns.append(log.get('request', {}).get('context', {}).get('conversation', 'N/A'))

Or better still, use a try/except to append the default value if any of the keys in missing:

try:
    logcolumns.append(log['request']['context']['conversation_id'])
except KeyError:
    logcolumns.append('N/A')

Upvotes: 2

Related Questions