【问题标题】:Convert JSON null to nan in simplejson.load()?在 simplejson.load() 中将 JSON null 转换为 nan?
【发布时间】:2018-09-24 12:56:06
【问题描述】:

我一直在使用simplejson 模块来正确处理所有 NaN --> null 转换(从 python 到 json)。具体来说:

  • 我一直在 ignore_nan=True 函数中使用 ignore_nan=True 标志)。
  • 我似乎找不到相反的等效功能,即 从 JSON null 到 nan - 使用 simplejson.load 函数。默认值似乎是将空值读入None

如何做到这一点?

【问题讨论】:

    标签: python json null nan simplejson


    【解决方案1】:

    为了它的价值 - 我最终制作了以下功能来实现我想要的(需要 math 模块):

    def convert(d):
        if isinstance(d,dict):
            yield {k:v for k,v in dict_convert(d)}
        elif isinstance(d,list):
            yield list_convert(d)
        else:
            yield d 
    
    def list_convert(d):
        return [math.nan if i is None else i for i in d]
    
    def dict_convert(d):
        for key, value in d.items():
            yield key, [i for i in convert(value)][0]
    
    #d_in = JSON data, containing nulls
    #d_out = JSON data, with null converted to nan
    
    d_out = [i for i in test_opennem.convert(d_in)][0]      
    

    对我来说似乎适用于任何d_in JSON 结构,(无论有多少嵌套组件)......虽然没有经过广泛测试,并且可能不适合所有情况等。

    也只将列表中的空值转换为 NaN,(不是字典键或其他字符串转换为 NaN)——这在我的情况下也很好。

    【讨论】:

      猜你喜欢
      • 2015-04-22
      • 2018-06-26
      • 2020-12-10
      • 2023-01-20
      • 1970-01-01
      • 2016-06-25
      • 2011-11-24
      • 1970-01-01
      • 2017-04-23
      相关资源
      最近更新 更多