frazman
frazman

Reputation: 33243

check for null fields in json python

A very naive question but is there a robust or better way to do following. Say it has nothing to do with json actually.

let say I have list (reading from file)

string_list = [ "foo",1,None, "null","[]","bar"]

Now, null and [] are essentially equivalent of null but different data structures have different interpretation of "None"?? right?

So rather than me writing a regex for all these rules.. is there a better way to convert "null","[]" etc to None.. ??

Thanks

Upvotes: 1

Views: 4589

Answers (3)

7stud
7stud

Reputation: 48599

1) You shouldn't be converting anything to None.

2) The first thing you want to do is convert to json. The json module will convert null to None, so you don't have to worry about null. And empty json strings, arrays, and objects, will be converted to empty python strings, lists, and dicts, so you won't be dealing with strings at all.

3) Then if you want to filter out the empty objects, you can do things like this:

import json

my_data = json.loads("""
    [
        "hello", 
        "", 
        [], 
        {}, 
        [1, 2, 3], 
        {"a": 1, "b": 2}
    ] 
""")

print(my_data)
print([x for x in my_data if x])

--output:--
['hello', '', [], {}, [1, 2, 3], {'a': 1, 'b': 2}]
['hello', [1, 2, 3], {'a': 1, 'b': 2}]

Empty objects(including 0) evaluate to False.

Upvotes: 1

alecxe
alecxe

Reputation: 473873

Define a set of values that should be replaced with None and use list comprehension to "replace" them:

>>> string_list = [ "foo",1,None, "null","[]","bar"]
>>> none_items = {"null", "[]"}  # or set(("null", "[]"))
>>> [None if item in none_items else item for item in string_list]
['foo', 1, None, None, None, 'bar']

Or, use map():

>>> map(lambda x: None if x in none_items else x, string_list)
['foo', 1, None, None, None, 'bar']

Using set because of O(1) lookups.

Upvotes: 2

AChampion
AChampion

Reputation: 30258

You could try:

string_list = [ "foo",1,None, "null","[]","bar"]
nones = [ "null", "[]" ]
print([None if s in nones else s for s in string_list])

Upvotes: 1

Related Questions