Remove all last commas between brackets

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
7
down vote

favorite












I'm trying to format the following as JSON (in Python):




"sessionTimeout":"3600.0",
"serverVersion":"LK_LK-NL-7_188-176-419",
"worldDawn":"2018-10-09 06:00:00 Etc/GMT",
"Data":
"Player":[

"nick":"Player11226400",
"points":"44",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5048",
"rank":"561",
"entityName":"Player",
,

"nick":"Player11230580",
"points":"15",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5215",
"rank":"2081",
"entityName":"Player",
,

"nick":"Player11291581",
"points":"15",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5942",
"rank":"2081",
"entityName":"Player",

]




Every JSON validator of course tells me that this is not valid JSON because of the trailing "," before each }, so I want to remove that comma. I tried removing them with .replace('"Player",", '"Player"') but I don't consider this as a good solution. This because I also have trailing "," in for example a Alliance or Habitat string ("Habitat", & "Alliance",)



Could anyone help me with finding a better solution to this problem?










share|improve this question





















  • is this in a text file, or in python code??
    – blue_note
    42 mins ago










  • @blue_note This is a string in Python, an endpoint response.
    – Sander Bakker
    40 mins ago







  • 1




    A hacky solution could be .replace(",n}", "n}"). Although the best solution would be to generate the JSON correctly if possible.
    – Carlos Gonzalez
    40 mins ago











  • @CarlosGonzalez That does not seems to work
    – Sander Bakker
    39 mins ago










  • With SublimeText editor I used this regex to find all of the problematic "," characters: ",n .*}. You can also use this regex in your python code (but I didn't try, so I do not post the code).
    – Ptaq666
    38 mins ago














up vote
7
down vote

favorite












I'm trying to format the following as JSON (in Python):




"sessionTimeout":"3600.0",
"serverVersion":"LK_LK-NL-7_188-176-419",
"worldDawn":"2018-10-09 06:00:00 Etc/GMT",
"Data":
"Player":[

"nick":"Player11226400",
"points":"44",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5048",
"rank":"561",
"entityName":"Player",
,

"nick":"Player11230580",
"points":"15",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5215",
"rank":"2081",
"entityName":"Player",
,

"nick":"Player11291581",
"points":"15",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5942",
"rank":"2081",
"entityName":"Player",

]




Every JSON validator of course tells me that this is not valid JSON because of the trailing "," before each }, so I want to remove that comma. I tried removing them with .replace('"Player",", '"Player"') but I don't consider this as a good solution. This because I also have trailing "," in for example a Alliance or Habitat string ("Habitat", & "Alliance",)



Could anyone help me with finding a better solution to this problem?










share|improve this question





















  • is this in a text file, or in python code??
    – blue_note
    42 mins ago










  • @blue_note This is a string in Python, an endpoint response.
    – Sander Bakker
    40 mins ago







  • 1




    A hacky solution could be .replace(",n}", "n}"). Although the best solution would be to generate the JSON correctly if possible.
    – Carlos Gonzalez
    40 mins ago











  • @CarlosGonzalez That does not seems to work
    – Sander Bakker
    39 mins ago










  • With SublimeText editor I used this regex to find all of the problematic "," characters: ",n .*}. You can also use this regex in your python code (but I didn't try, so I do not post the code).
    – Ptaq666
    38 mins ago












up vote
7
down vote

favorite









up vote
7
down vote

favorite











I'm trying to format the following as JSON (in Python):




"sessionTimeout":"3600.0",
"serverVersion":"LK_LK-NL-7_188-176-419",
"worldDawn":"2018-10-09 06:00:00 Etc/GMT",
"Data":
"Player":[

"nick":"Player11226400",
"points":"44",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5048",
"rank":"561",
"entityName":"Player",
,

"nick":"Player11230580",
"points":"15",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5215",
"rank":"2081",
"entityName":"Player",
,

"nick":"Player11291581",
"points":"15",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5942",
"rank":"2081",
"entityName":"Player",

]




Every JSON validator of course tells me that this is not valid JSON because of the trailing "," before each }, so I want to remove that comma. I tried removing them with .replace('"Player",", '"Player"') but I don't consider this as a good solution. This because I also have trailing "," in for example a Alliance or Habitat string ("Habitat", & "Alliance",)



Could anyone help me with finding a better solution to this problem?










share|improve this question













I'm trying to format the following as JSON (in Python):




"sessionTimeout":"3600.0",
"serverVersion":"LK_LK-NL-7_188-176-419",
"worldDawn":"2018-10-09 06:00:00 Etc/GMT",
"Data":
"Player":[

"nick":"Player11226400",
"points":"44",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5048",
"rank":"561",
"entityName":"Player",
,

"nick":"Player11230580",
"points":"15",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5215",
"rank":"2081",
"entityName":"Player",
,

"nick":"Player11291581",
"points":"15",
"alliancePermission":"0",
"isOnVacation":"false",
"id":"5942",
"rank":"2081",
"entityName":"Player",

]




Every JSON validator of course tells me that this is not valid JSON because of the trailing "," before each }, so I want to remove that comma. I tried removing them with .replace('"Player",", '"Player"') but I don't consider this as a good solution. This because I also have trailing "," in for example a Alliance or Habitat string ("Habitat", & "Alliance",)



Could anyone help me with finding a better solution to this problem?







python json






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 44 mins ago









Sander Bakker

14911




14911











  • is this in a text file, or in python code??
    – blue_note
    42 mins ago










  • @blue_note This is a string in Python, an endpoint response.
    – Sander Bakker
    40 mins ago







  • 1




    A hacky solution could be .replace(",n}", "n}"). Although the best solution would be to generate the JSON correctly if possible.
    – Carlos Gonzalez
    40 mins ago











  • @CarlosGonzalez That does not seems to work
    – Sander Bakker
    39 mins ago










  • With SublimeText editor I used this regex to find all of the problematic "," characters: ",n .*}. You can also use this regex in your python code (but I didn't try, so I do not post the code).
    – Ptaq666
    38 mins ago
















  • is this in a text file, or in python code??
    – blue_note
    42 mins ago










  • @blue_note This is a string in Python, an endpoint response.
    – Sander Bakker
    40 mins ago







  • 1




    A hacky solution could be .replace(",n}", "n}"). Although the best solution would be to generate the JSON correctly if possible.
    – Carlos Gonzalez
    40 mins ago











  • @CarlosGonzalez That does not seems to work
    – Sander Bakker
    39 mins ago










  • With SublimeText editor I used this regex to find all of the problematic "," characters: ",n .*}. You can also use this regex in your python code (but I didn't try, so I do not post the code).
    – Ptaq666
    38 mins ago















is this in a text file, or in python code??
– blue_note
42 mins ago




is this in a text file, or in python code??
– blue_note
42 mins ago












@blue_note This is a string in Python, an endpoint response.
– Sander Bakker
40 mins ago





@blue_note This is a string in Python, an endpoint response.
– Sander Bakker
40 mins ago





1




1




A hacky solution could be .replace(",n}", "n}"). Although the best solution would be to generate the JSON correctly if possible.
– Carlos Gonzalez
40 mins ago





A hacky solution could be .replace(",n}", "n}"). Although the best solution would be to generate the JSON correctly if possible.
– Carlos Gonzalez
40 mins ago













@CarlosGonzalez That does not seems to work
– Sander Bakker
39 mins ago




@CarlosGonzalez That does not seems to work
– Sander Bakker
39 mins ago












With SublimeText editor I used this regex to find all of the problematic "," characters: ",n .*}. You can also use this regex in your python code (but I didn't try, so I do not post the code).
– Ptaq666
38 mins ago




With SublimeText editor I used this regex to find all of the problematic "," characters: ",n .*}. You can also use this regex in your python code (but I didn't try, so I do not post the code).
– Ptaq666
38 mins ago












3 Answers
3






active

oldest

votes

















up vote
5
down vote



accepted










Two solutions:



First one, cool if your json file doesn't have null or false/true booleans would be to read the input using ast.literal_eval which can process those commas, then dump back the dict as json if needed:



d = ast.literal_eval(txt)
print(json.dumps(d,indent=4))


if you can't, you can use a regex to remove commas that happen before a newline if the next line starts with spaces + closing braces/brackets:



import re

print(json.loads(re.sub(",(ns+[}]])",r"1",txt)))


here's a full snippet containing the 2 approaches with a cut-down version of your input:



import ast,json

txt = """
"sessionTimeout":"3600.0",
"serverVersion":"LK_LK-NL-7_188-176-419",
"worldDawn":"2018-10-09 06:00:00 Etc/GMT",
"Data":
"Player":[

"nick":"Player11226400",
"rank":"561",
"entityName":"Player",
,

"nick":"Player11230580",
"rank":"2081",
"entityName":"Player",
,

"nick":"Player11291581",
"rank":"2081",
"entityName":"Player",

]

"""

print("ast literal eval:")
d = ast.literal_eval(txt)
print(json.dumps(d,indent=4))

import re

print("regex:")
d = json.loads(re.sub(",(ns+[}]])",r"1",txt))
print(json.dumps(d,indent=4))


both methods successfully parse your input file. The first method will work flawlessly as long as there are no null pointers & booleans, the second method may fail in some obscure formatting cases. In case of bad luck, you can hack something in between.






share|improve this answer



























    up vote
    2
    down vote













    Since JSON is a subset of YAML, where dangling commas are permitted, you can use a yaml parser here.



    pip install pyyaml


    The library has a load function, similar to the standard library json.loads.



    import json, yaml
    json.dumps(yaml.load(jsondata))


    You can also use ast.literal_eval for this particular data. But unlike pyyaml that doesn't work if your json contains literal false, true or null values.






    share|improve this answer





























      up vote
      0
      down vote













      Use python's json module to export python dict to valid json:



      import json
      json.dumps(<your-dict>)





      share|improve this answer
















      • 1




        The OP does not have a dictionary, just a bad formatted text.
        – toti08
        33 mins ago










      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',
      convertImagesToLinks: true,
      noModals: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      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%2f52698573%2fremove-all-last-commas-between-brackets%23new-answer', 'question_page');

      );

      Post as a guest






























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      5
      down vote



      accepted










      Two solutions:



      First one, cool if your json file doesn't have null or false/true booleans would be to read the input using ast.literal_eval which can process those commas, then dump back the dict as json if needed:



      d = ast.literal_eval(txt)
      print(json.dumps(d,indent=4))


      if you can't, you can use a regex to remove commas that happen before a newline if the next line starts with spaces + closing braces/brackets:



      import re

      print(json.loads(re.sub(",(ns+[}]])",r"1",txt)))


      here's a full snippet containing the 2 approaches with a cut-down version of your input:



      import ast,json

      txt = """
      "sessionTimeout":"3600.0",
      "serverVersion":"LK_LK-NL-7_188-176-419",
      "worldDawn":"2018-10-09 06:00:00 Etc/GMT",
      "Data":
      "Player":[

      "nick":"Player11226400",
      "rank":"561",
      "entityName":"Player",
      ,

      "nick":"Player11230580",
      "rank":"2081",
      "entityName":"Player",
      ,

      "nick":"Player11291581",
      "rank":"2081",
      "entityName":"Player",

      ]

      """

      print("ast literal eval:")
      d = ast.literal_eval(txt)
      print(json.dumps(d,indent=4))

      import re

      print("regex:")
      d = json.loads(re.sub(",(ns+[}]])",r"1",txt))
      print(json.dumps(d,indent=4))


      both methods successfully parse your input file. The first method will work flawlessly as long as there are no null pointers & booleans, the second method may fail in some obscure formatting cases. In case of bad luck, you can hack something in between.






      share|improve this answer
























        up vote
        5
        down vote



        accepted










        Two solutions:



        First one, cool if your json file doesn't have null or false/true booleans would be to read the input using ast.literal_eval which can process those commas, then dump back the dict as json if needed:



        d = ast.literal_eval(txt)
        print(json.dumps(d,indent=4))


        if you can't, you can use a regex to remove commas that happen before a newline if the next line starts with spaces + closing braces/brackets:



        import re

        print(json.loads(re.sub(",(ns+[}]])",r"1",txt)))


        here's a full snippet containing the 2 approaches with a cut-down version of your input:



        import ast,json

        txt = """
        "sessionTimeout":"3600.0",
        "serverVersion":"LK_LK-NL-7_188-176-419",
        "worldDawn":"2018-10-09 06:00:00 Etc/GMT",
        "Data":
        "Player":[

        "nick":"Player11226400",
        "rank":"561",
        "entityName":"Player",
        ,

        "nick":"Player11230580",
        "rank":"2081",
        "entityName":"Player",
        ,

        "nick":"Player11291581",
        "rank":"2081",
        "entityName":"Player",

        ]

        """

        print("ast literal eval:")
        d = ast.literal_eval(txt)
        print(json.dumps(d,indent=4))

        import re

        print("regex:")
        d = json.loads(re.sub(",(ns+[}]])",r"1",txt))
        print(json.dumps(d,indent=4))


        both methods successfully parse your input file. The first method will work flawlessly as long as there are no null pointers & booleans, the second method may fail in some obscure formatting cases. In case of bad luck, you can hack something in between.






        share|improve this answer






















          up vote
          5
          down vote



          accepted







          up vote
          5
          down vote



          accepted






          Two solutions:



          First one, cool if your json file doesn't have null or false/true booleans would be to read the input using ast.literal_eval which can process those commas, then dump back the dict as json if needed:



          d = ast.literal_eval(txt)
          print(json.dumps(d,indent=4))


          if you can't, you can use a regex to remove commas that happen before a newline if the next line starts with spaces + closing braces/brackets:



          import re

          print(json.loads(re.sub(",(ns+[}]])",r"1",txt)))


          here's a full snippet containing the 2 approaches with a cut-down version of your input:



          import ast,json

          txt = """
          "sessionTimeout":"3600.0",
          "serverVersion":"LK_LK-NL-7_188-176-419",
          "worldDawn":"2018-10-09 06:00:00 Etc/GMT",
          "Data":
          "Player":[

          "nick":"Player11226400",
          "rank":"561",
          "entityName":"Player",
          ,

          "nick":"Player11230580",
          "rank":"2081",
          "entityName":"Player",
          ,

          "nick":"Player11291581",
          "rank":"2081",
          "entityName":"Player",

          ]

          """

          print("ast literal eval:")
          d = ast.literal_eval(txt)
          print(json.dumps(d,indent=4))

          import re

          print("regex:")
          d = json.loads(re.sub(",(ns+[}]])",r"1",txt))
          print(json.dumps(d,indent=4))


          both methods successfully parse your input file. The first method will work flawlessly as long as there are no null pointers & booleans, the second method may fail in some obscure formatting cases. In case of bad luck, you can hack something in between.






          share|improve this answer












          Two solutions:



          First one, cool if your json file doesn't have null or false/true booleans would be to read the input using ast.literal_eval which can process those commas, then dump back the dict as json if needed:



          d = ast.literal_eval(txt)
          print(json.dumps(d,indent=4))


          if you can't, you can use a regex to remove commas that happen before a newline if the next line starts with spaces + closing braces/brackets:



          import re

          print(json.loads(re.sub(",(ns+[}]])",r"1",txt)))


          here's a full snippet containing the 2 approaches with a cut-down version of your input:



          import ast,json

          txt = """
          "sessionTimeout":"3600.0",
          "serverVersion":"LK_LK-NL-7_188-176-419",
          "worldDawn":"2018-10-09 06:00:00 Etc/GMT",
          "Data":
          "Player":[

          "nick":"Player11226400",
          "rank":"561",
          "entityName":"Player",
          ,

          "nick":"Player11230580",
          "rank":"2081",
          "entityName":"Player",
          ,

          "nick":"Player11291581",
          "rank":"2081",
          "entityName":"Player",

          ]

          """

          print("ast literal eval:")
          d = ast.literal_eval(txt)
          print(json.dumps(d,indent=4))

          import re

          print("regex:")
          d = json.loads(re.sub(",(ns+[}]])",r"1",txt))
          print(json.dumps(d,indent=4))


          both methods successfully parse your input file. The first method will work flawlessly as long as there are no null pointers & booleans, the second method may fail in some obscure formatting cases. In case of bad luck, you can hack something in between.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 38 mins ago









          Jean-François Fabre

          93.4k847103




          93.4k847103






















              up vote
              2
              down vote













              Since JSON is a subset of YAML, where dangling commas are permitted, you can use a yaml parser here.



              pip install pyyaml


              The library has a load function, similar to the standard library json.loads.



              import json, yaml
              json.dumps(yaml.load(jsondata))


              You can also use ast.literal_eval for this particular data. But unlike pyyaml that doesn't work if your json contains literal false, true or null values.






              share|improve this answer


























                up vote
                2
                down vote













                Since JSON is a subset of YAML, where dangling commas are permitted, you can use a yaml parser here.



                pip install pyyaml


                The library has a load function, similar to the standard library json.loads.



                import json, yaml
                json.dumps(yaml.load(jsondata))


                You can also use ast.literal_eval for this particular data. But unlike pyyaml that doesn't work if your json contains literal false, true or null values.






                share|improve this answer
























                  up vote
                  2
                  down vote










                  up vote
                  2
                  down vote









                  Since JSON is a subset of YAML, where dangling commas are permitted, you can use a yaml parser here.



                  pip install pyyaml


                  The library has a load function, similar to the standard library json.loads.



                  import json, yaml
                  json.dumps(yaml.load(jsondata))


                  You can also use ast.literal_eval for this particular data. But unlike pyyaml that doesn't work if your json contains literal false, true or null values.






                  share|improve this answer














                  Since JSON is a subset of YAML, where dangling commas are permitted, you can use a yaml parser here.



                  pip install pyyaml


                  The library has a load function, similar to the standard library json.loads.



                  import json, yaml
                  json.dumps(yaml.load(jsondata))


                  You can also use ast.literal_eval for this particular data. But unlike pyyaml that doesn't work if your json contains literal false, true or null values.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 24 mins ago

























                  answered 29 mins ago









                  HÃ¥ken Lid

                  8,88052239




                  8,88052239




















                      up vote
                      0
                      down vote













                      Use python's json module to export python dict to valid json:



                      import json
                      json.dumps(<your-dict>)





                      share|improve this answer
















                      • 1




                        The OP does not have a dictionary, just a bad formatted text.
                        – toti08
                        33 mins ago














                      up vote
                      0
                      down vote













                      Use python's json module to export python dict to valid json:



                      import json
                      json.dumps(<your-dict>)





                      share|improve this answer
















                      • 1




                        The OP does not have a dictionary, just a bad formatted text.
                        – toti08
                        33 mins ago












                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      Use python's json module to export python dict to valid json:



                      import json
                      json.dumps(<your-dict>)





                      share|improve this answer












                      Use python's json module to export python dict to valid json:



                      import json
                      json.dumps(<your-dict>)






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 37 mins ago









                      Sanchit

                      6614




                      6614







                      • 1




                        The OP does not have a dictionary, just a bad formatted text.
                        – toti08
                        33 mins ago












                      • 1




                        The OP does not have a dictionary, just a bad formatted text.
                        – toti08
                        33 mins ago







                      1




                      1




                      The OP does not have a dictionary, just a bad formatted text.
                      – toti08
                      33 mins ago




                      The OP does not have a dictionary, just a bad formatted text.
                      – toti08
                      33 mins ago

















                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52698573%2fremove-all-last-commas-between-brackets%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Comments

                      Popular posts from this blog

                      What does second last employer means? [closed]

                      List of Gilmore Girls characters

                      Confectionery