如何将“无”值替换为“无”字符串值

时间:2019-03-22 18:38:24

标签: python-3.x

我有一个要写入JSON文件的文本文件。一些值将返回为None,True或False。我需要将“无”替换为“无”(字符串),将“真”替换为“真”,将“假”替换为“假”

我尝试添加行

data=data.replace(None,"None")

但是,我得到一个错误

Traceback (most recent call last):
  File "parse_get_drivers.py", line 17, in <module>
    data=data.replace(None,"None")
TypeError: replace() argument 1 must be str, not None
  

这是我的剧本

import json
import re
from pprint import pprint
import pandas as pd

inHandler = open('get_drivers.txt', 'r')
outHandler = open('drivers.json', 'w')
data = ''


for line in inHandler.readlines():
    print('src:' + line)
    line = line.replace("}]},","}]},\r")
    data += line
    print('replace:' + line)
    data=data.replace("'", '"')
    data=data.replace(None,"None")

outHandler.write(data)

inHandler.close()
outHandler.close()

所需结果是将“无”,“真”和“假”值替换为“无”,“真”和“假”。

1 个答案:

答案 0 :(得分:1)

您应该将输入解析为JSON,而不是逐行解析为单独的字符串,以便您可以递归遍历数据结构以将None(或以JSON的术语,null)替换为"None"

def replace(data, search, replacement, parent=None, index=None):
    if data == search:
        parent[index] = replacement
    elif isinstance(data, (list, dict)):
        for index, item in enumerate(data) if isinstance(data, list) else data.items():
            replace(item, search, replacement, parent=data, index=index)

这样:

import json
d = json.loads('{"a": 1, "b": [1, null], "c": {"d": null}}')
print(d)
replace(d, None, 'None')
print(d)
print(json.dumps(d))

输出:

{'a': 1, 'b': [1, None], 'c': {'d': None}}
{'a': 1, 'b': [1, 'None'], 'c': {'d': 'None'}}
{"a": 1, "b": [1, "None"], "c": {"d": "None"}}