Python替换嵌套JSON中的None值 [英] Python replace None values in nested JSON

查看:849
本文介绍了Python替换嵌套JSON中的None值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力替换下面的JSON字典中的None值.我将如何遍历此json,并将"None"值替换为空字符串?我很难理解如何遍历嵌套的json.如果有人可以帮助我,我会很乐意.下面是嵌套json的示例. 或使用python中的Requests库执行获取"请求时,是否可以替换值(例如,从None到空字符串)?

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
}

推荐答案

import json

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

退出:

 {'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'}}

将其转换为字符串并将null(string)替换为"",然后将其加载回python dict

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

这篇关于Python替换嵌套JSON中的None值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆