[英]How json dumps None to empty string
我希望 Python 的None
在 json 中編碼為空字符串如何? 下面是json.dumps
的默認行為。
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
我應該覆蓋 json 編碼器方法還是有其他方法?
輸入數據並不像上面的例子那么簡單,在每次請求時,它都可以更改為不同的數據結構。 很難寫一個 function 來改變數據結構。
在您正在編碼的 object 中,使用空字符串而不是None
。
這是一個未經測試的 function 遍歷一系列嵌套字典以將所有None
值更改為''
。 添加對列表和元組的支持留給讀者作為練習。:)
import copy
def scrub(x):
ret = copy.deepcopy(x)
# Handle dictionaries. Scrub all values
if isinstance(x, dict):
for k,v in ret.items():
ret[k] = scrub(v)
# Handle None
if x == None:
ret = ''
# Finished scrubbing
return ret
處理要編碼的數據並用空字符串替換None
會更好。 畢竟,這就是你想要的。
這是一個稍微改進的版本,它也可以處理列表和元組:
def scrub(x):
# Converts None to empty string
ret = copy.deepcopy(x)
# Handle dictionaries, lits & tuples. Scrub all values
if isinstance(x, dict):
for k, v in ret.items():
ret[k] = scrub(v)
if isinstance(x, (list, tuple)):
for k, v in enumerate(ret):
ret[k] = scrub(v)
# Handle None
if x is None:
ret = ''
# Finished scrubbing
return ret
我在使用jsonschmea
模塊時使用它。 似乎它無法處理None
類型,並拋出: jsonschema.exceptions.ValidationError: None is not of type u'string'
。 所以這可以解決問題。
您實際上可以使用json.JSONEncoder ,如果您有一個帶有列表、元組、字典、字符串和 None 的 object,您可以使用 class 來替換之后顯示的空字符串。
default
是原先用於將非 json 類型轉換為 python 的方法,這次我們使用它來將 None 轉換為空字符串。
encode
用於對 json 進行編碼,這就是我們使用新默認值使用新方法的原因
class NoneToEmptyJSON(json.JSONEncoder):
def default(self, o):
if o == None:
o = ''
elif type(o) == dict:
return {self.default(key): self.default(value) for key, value in o.items()}
elif type(o) == list or type(o) == tuple:
return [self.default(item) for item in o]
return o
def encode(self, o):
return super().encode(self.default(o))
然后代替轉儲,您使用 class 編碼
NoneToEmptyJSON().encode(['foo', {'bar': ('baz', None, 1.0, 2)}])
那么結果是:
'["foo", {"bar": ["baz", "", 1.0, 2]}]'
如果你想要縮進或其他東西,你也可以使用 params :
NoneToEmptyJSON(ensure_ascii=False, indent=2).encode(['foo', {'bar': ('baz', None, 1.0, 2)}])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.