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
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;








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










share|improve this question



















  • 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

















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










share|improve this question



















  • 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













1












1








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










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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












  • 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







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












1 Answer
1






active

oldest

votes


















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"





share|improve this answer

























    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
    );



    );













    draft saved

    draft discarded


















    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









    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"





    share|improve this answer





























      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"





      share|improve this answer



























        1












        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"





        share|improve this answer















        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"






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 22 at 18:57

























        answered Mar 22 at 18:52









        blhsingblhsing

        45.5k51747




        45.5k51747





























            draft saved

            draft discarded
















































            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.




            draft saved


            draft discarded














            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





















































            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
            sUHfAI 4Rik9ASyTNeaz Gpqi,AgP0rH0WwMXMvCdYCqEg63sm sexjWDatOYQ94nIT

            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            위키백과:대문 둘러보기 메뉴기부 안내모바일판 대문크리에이티브 커먼즈 저작자표시-동일조건변경허락 3.0CebuanoDeutschEnglishEspañolFrançaisItaliano日本語NederlandsPolskiPortuguêsРусскийSvenskaTiếng ViệtWinaray中文العربيةCatalàفارسیSrpskiУкраїнськаБългарскиНохчийнČeštinaDanskEsperantoEuskaraSuomiעבריתMagyarՀայերենBahasa IndonesiaҚазақшаBaso MinangkabauBahasa MelayuBân-lâm-gúNorskRomânăSrpskohrvatskiSlovenčinaTürkçe