1

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".

1
  • 1
    This makes no sense. Use json.loads, and especially if you are not loading the JSON, True/False/None should already be string values. Commented Mar 22, 2019 at 18:40

1 Answer 1

1

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"}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.