How to replace None value with “None” string valueConvert bytes to a string?AttributeError: 'module' object has no attribute 'urlopen'pandas DataFrame.replace function broken for datetimeConvertin string of list to list of floats [pandas]Str Object is not Callable; Python Dictionary Loop Errorxlwt book.save TypeError: must be str, not bytesI am getting these error:TypeError: avg_1() takes 0 positional arguments but 1 was given(python) Accessing nested value on JSON if list not empty,How to replace a string with a pattern using reg.expressionCreating a custom format specifier in __format__ method in python

Multi tool use
Fizzy, soft, pop and still drinks
How to stop co-workers from teasing me because I know Russian?
Shrinkwrap tetris shapes without scaling or diagonal shapes
Pass By Reference VS Pass by Value
What makes accurate emulation of old systems a difficult task?
Why was Germany not as successful as other Europeans in establishing overseas colonies?
Does this extra sentence in the description of the warlock's Eyes of the Rune Keeper eldritch invocation appear in any official reference?
Apply MapThread to all but one variable
What is the difference between `command a[bc]d` and `command `ab,cd`
Mac Pro install disk keeps ejecting itself
A Strange Latex Symbol
What language was spoken in East Asia before Proto-Turkic?
How to pronounce 'C++' in Spanish
Is contacting this expert in the field something acceptable or would it be discourteous?
Do I have to worry about players making “bad” choices on level up?
a sore throat vs a strep throat vs strep throat
How can the Zone of Truth spell be defeated without the caster knowing?
What's the polite way to say "I need to urinate"?
What are the potential pitfalls when using metals as a currency?
how to sum variables from file in bash
Can someone publish a story that happened to you?
Uniformly continuous derivative implies existence of limit
Reducing vertical space in stackrel
Why isn't the definition of absolute value applied when squaring a radical containing a variable?
How to replace None value with “None” string value
Convert bytes to a string?AttributeError: 'module' object has no attribute 'urlopen'pandas DataFrame.replace function broken for datetimeConvertin string of list to list of floats [pandas]Str Object is not Callable; Python Dictionary Loop Errorxlwt book.save TypeError: must be str, not bytesI am getting these error:TypeError: avg_1() takes 0 positional arguments but 1 was given(python) Accessing nested value on JSON if list not empty,How to replace a string with a pattern using reg.expressionCreating a custom format specifier in __format__ method in python
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
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".
python-3.x
add a comment |
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".
python-3.x
1
This makes no sense. Usejson.loads
, and especially if you are not loading the JSON,True
/False
/None
should already be string values.
– connectyourcharger
Mar 22 at 18:40
add a comment |
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".
python-3.x
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".
python-3.x
python-3.x
edited Mar 22 at 18:41


Carcigenicate
18.7k53262
18.7k53262
asked Mar 22 at 18:38


Gary GlasspoolGary Glasspool
305
305
1
This makes no sense. Usejson.loads
, and especially if you are not loading the JSON,True
/False
/None
should already be string values.
– connectyourcharger
Mar 22 at 18:40
add a comment |
1
This makes no sense. Usejson.loads
, and especially if you are not loading the JSON,True
/False
/None
should already be string values.
– connectyourcharger
Mar 22 at 18:40
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.– connectyourcharger
Mar 22 at 18:40
This makes no sense. Use
json.loads
, and especially if you are not loading the JSON, True
/False
/None
should already be string values.– connectyourcharger
Mar 22 at 18:40
add a comment |
1 Answer
1
active
oldest
votes
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"
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55305929%2fhow-to-replace-none-value-with-none-string-value%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
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"
add a comment |
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"
add a comment |
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"
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"
edited Mar 22 at 18:57
answered Mar 22 at 18:52
blhsingblhsing
45.5k51747
45.5k51747
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55305929%2fhow-to-replace-none-value-with-none-string-value%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
yBESGPt3Qrr71x7 DL,JY,rH,BkkPS8fToO jAmv e87Kiw5nnWzTq CxvgcBh7bSgZmJX blXvQsW VYGPjB0kqviPyOa,tIgrU,h 3X4
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.– connectyourcharger
Mar 22 at 18:40