2

I have been trying to wrap my head around replacing the None values in the JSON dictionary below. How would I traverse this json, and replace the "None" values with empty strings? I'm having difficulty understanding how to traverse nested json. Would love if someone can help me with this. Example nested json below. OR is there a way to replace values (such as from None to empty string) when using doing a "get" request with the Requests library in python?

{  
   'house':{  
      'amount':'$0.00',
      'id':1,
      'value':0.0
   },
   'event':'12.199.136.146',
   'location':'',
   'language':{  
      'language_name':'English',
      'language_id':1,
      'language_symbol':None
   },
   'percentage':1.0,
   'identification':'',
   'source':{  
      'name':'john',
      'id':-1
   },
   'paid':{  
      'amount':'$0.00',
      'format':1,
      'value':0.0
   },
   'score':None
}
pppp
  • 557
  • 3
  • 8
  • 21

2 Answers2

9
import json

r = json.dumps(j).replace('null', '""')
json.loads(r)

out:

 {'event': '12.199.136.146',
 'house': {'amount': '$0.00', 'id': 1, 'value': 0.0},
 'identification': '',
 'language': {'language_id': 1,
  'language_name': 'English',
  'language_symbol': ''},
 'location': '',
 'paid': {'amount': '$0.00', 'format': 1, 'value': 0.0},
 'percentage': 1.0,
 'score': '',
 'source': {'id': -1, 'name': 'john'}}

convert it to string and replace null(string) to "", and load it back to python dict

宏杰李
  • 11,820
  • 2
  • 28
  • 35
  • 6
    `{"name":"Bobby null Tables"}` – Josh Lee Jan 18 '17 at 02:34
  • 1
    This will replace any occurrences of "null" in the JSON string, which is incorrect. As noted by Josh Lee in the comment above, for example, `{"name":"Bobby null Tables"}` would be changed to `{"name":"Bobby "" Tables"}`, probably not what you want. – Barry May 25 '21 at 13:59
2

Try it:

#!/usr/bin/python3
import json
from pprint import pprint

jstr = {  
   'house':{  
      'amount':'$0.00',
      'id':1,
      'value':0.0
   },
   'event':'12.199.136.146',
   'location':'',
   'language':{  
      'language_name':'English',
      'language_id':1,
      'language_symbol':None
   },
   'percentage':1.0,
   'identification':'',
   'source':{  
      'name':'john',
      'id':-1
   },
   'paid':{  
      'amount':'$0.00',
      'format':1,
      'value':0.0
   },
   'score':None
}

data_str = json.dumps(jstr)
data = json.loads(data_str)
pprint(data)


def replaceNone(data_dict,v,rv):
    for key in data_dict.keys():
        if data_dict[key] == v:
            data_dict[key] = rv
        elif type(data_dict[key]) is dict:
            replaceNone(data_dict[key],v,rv)


replaceNone(data,None,"")
pprint(data)
Harper Koo
  • 597
  • 5
  • 14
  • This looks like it will work, but the function name is confusing: although the function is called`replaceNone`, it will actually replace any dictionary value `v` with the specified value `rv`. – Barry May 25 '21 at 14:01