Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python replace None values in nested JSON

Tags:

python

json

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
}
like image 767
Paul Avatar asked Feb 04 '26 00:02

Paul


1 Answers

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

like image 171
宏杰李 Avatar answered Feb 05 '26 14:02

宏杰李