1

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

3
  • That's a list, not a string. Commented Sep 17, 2013 at 22:34
  • My bad.. originally i thought of posting what i was facing.. (reading json strings in file with such fields).. but then realized that a simple list with such values will also explain the issue Commented Sep 17, 2013 at 22:36
  • It'd be better to show us a sample of the JSON than to show how you'd represent it in python. Considering that null and [] are both valid in JSON, and that things like len([]) works while len(None) does not, flattening all instances of empty lists to None might not be the best approach. Commented Sep 17, 2013 at 22:41

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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])

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.