1

I am using a third party API which gives me a JSON response as follows.

{
   "peopleList":[
      {
         "name":"Jack",
         "creditcard":"12335435345"
      },
      {
         "name":"Arya",
         "creditcard":""
      }
   ],
   "responseTime":0.02,
   "error":""
}

Here the empty string is used to represent No Value, which I think should have been null.
How do I replace all the values that are empty-string to null using python?

Edit:
I am using Django to serve JSON to my iOS app which is in Swift. Although empty string is false in python it is not the case in swift.

Or even better. How do I remove all the keys which have empty-strings as their value?

Kaunteya
  • 3,107
  • 1
  • 35
  • 66
  • 1
    Are you really want to do that? Why not exploit [false-like behavior of empty string](http://stackoverflow.com/questions/9573244/most-elegant-way-to-check-if-the-string-is-empty-in-python)? Same as `null`/`None` is falsy in Python. – Łukasz Rogalski Apr 23 '15 at 11:38
  • 3
    This is pretty bad practice from the side of the producer of the JSON - if there's no error, don't add it as a key. In addition to Vineet's answer you could instead remove the item from the dict instead of setting it to `None` which makes your intention clearer IMHO. – wonderb0lt Apr 23 '15 at 11:44
  • I have edited my answer. Should work for you. – Flame of udun Apr 23 '15 at 12:06
  • @wonderb0lt, I don't know if shouldn't be added as a key, but for sure if added, it should be ``null`` – bgusach Apr 23 '15 at 12:50

1 Answers1

4
data = json.loads(**your raw json string**)
nullify(data)
   
def nullify(container) :
 for key in container:
         if type(key) == list:
                 nullify(key)
         elif type(key) == dict:
                 nullify(key)
         elif type(container[key]) == dict or type(container[key]) == list:
                 nullify(container[key])
         elif container[key] == '':
                 container[key] = None

   

I believe this should work for you. Also, there is no null in python. Instead you can use None.

To remove the key altogether you must use container.pop(key,None). However you can't do it mid-iteration so you must store all such keys in a list and then pop them from the dictionary.

Braiam
  • 1
  • 11
  • 47
  • 78
Flame of udun
  • 2,136
  • 7
  • 35
  • 79
  • Your method fails in case the key is not an integer. It fails for first `if` clause `if container[key] == '':` It gives `TypeError: list indices must be integers, not dict` – Kaunteya Apr 23 '15 at 12:36