Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:替代`.replace(';null';,';';)`用嵌套JSON中的字符串替换null和None值_Python_Json - Fatal编程技术网

Python:替代`.replace(';null';,';';)`用嵌套JSON中的字符串替换null和None值

Python:替代`.replace(';null';,';';)`用嵌套JSON中的字符串替换null和None值,python,json,Python,Json,这是这个问题的后续问题 这使得该解决方案可以替换嵌套json中的所有None和null值 r = json.dumps(j).replace('null', '""') json.loads(r) 虽然这在大多数情况下都有效,但对于某些文件,我遇到了此错误 --------------------------------------------------------------------------- JSONDecodeError T

这是这个问题的后续问题

这使得该解决方案可以替换嵌套json中的所有
None
null

r = json.dumps(j).replace('null', '""')
json.loads(r)
虽然这在大多数情况下都有效,但对于某些文件,我遇到了此错误

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-39-9016b2aa3f6e> in <module>()
     55         parsed = json.load(f)
     56         r = json.dumps(parsed).replace('null',  '"NothingExistsHere"'  ) #remove all nulls and Nones and replace with empty strings
---> 57         parsed = json.loads(r)
     58 
     59     whichList = testDF.iloc[i]['AbstractHeader']

2 frames
/usr/lib/python3.6/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    352             parse_int is None and parse_float is None and
    353             parse_constant is None and object_pairs_hook is None and not kw):
--> 354         return _default_decoder.decode(s)
    355     if cls is None:
    356         cls = JSONDecoder

/usr/lib/python3.6/json/decoder.py in decode(self, s, _w)
    337 
    338         """
--> 339         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    340         end = _w(s, end).end()
    341         if end != len(s):

/usr/lib/python3.6/json/decoder.py in raw_decode(self, s, idx)
    353         """
    354         try:
--> 355             obj, end = self.scan_once(s, idx)
    356         except StopIteration as err:
    357             raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting ',' delimiter: line 1 column 24794 (char 24793)

分层数据的结构无关的字符串操作是一个问题——您应该在其核心解决这个问题,在您的案例中是JSON编码。遗憾的是,内置的
json
模块不允许轻松覆盖已知结构的默认行为,
None
就是其中之一。除非您想深入并覆盖(及其内部
\u iterencode\u*
方法)以迫使它屈服于您的意愿,或者使用另一种/较慢的JSON编码器,否则您最好的选择是预处理数据

这比你想象的要简单得多:

import json
from collections.abc import Mapping, Iterable

def replace_none(o, repl=''):
    if o is None:
        return repl
    if isinstance(o, Mapping):
        return {k: replace_none(v, repl) for k, v in o.items()}
    elif not isinstance(o, str) and isinstance(o, Iterable):
        return [replace_none(v, repl) for v in o]
    return o

# and to test it:
data = {'this': {'that': 'and', 'the': ['other thing', None]}}
r = json.dumps(replace_none(data))
# {"this": {"that": "and", "the": ["other thing", ""]}}

您的嵌套json看起来怎么样,请在问题中包括这一点,我更新了它,包括我正在使用的json对象
json.loads(json_string.replace('null','“”))
适用于给定的示例。这个错误可能发生在其他地方。
import json
from collections.abc import Mapping, Iterable

def replace_none(o, repl=''):
    if o is None:
        return repl
    if isinstance(o, Mapping):
        return {k: replace_none(v, repl) for k, v in o.items()}
    elif not isinstance(o, str) and isinstance(o, Iterable):
        return [replace_none(v, repl) for v in o]
    return o

# and to test it:
data = {'this': {'that': 'and', 'the': ['other thing', None]}}
r = json.dumps(replace_none(data))
# {"this": {"that": "and", "the": ["other thing", ""]}}