Reputation: 87
I have a text file that I am trying to write to a JSON file. Some of the values are returned as None, True or False. I need to replace None with "None" (string), True with "True" and False with "False"
I tried adding the line
data=data.replace(None,"None")
However, I get an error
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
Here is my script
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()
The required result is to replace None, True and False values with "None", "True" and "False".
Upvotes: 1
Views: 1966
Reputation: 106553
You should parse the input as JSON instead of parsing it line by line as separate strings, so that you can recursively traverse the data structure to replace None
(or in JSON's terms, null
) with "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)
so that:
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))
outputs:
{'a': 1, 'b': [1, None], 'c': {'d': None}}
{'a': 1, 'b': [1, 'None'], 'c': {'d': 'None'}}
{"a": 1, "b": [1, "None"], "c": {"d": "None"}}
Upvotes: 1