Remove trailing json comma with command line tools












2















I want to remove trailing comma from json as,



{
"key1": "value1",
"object": {
"key2": "value2", // <- remove comma
},
"key3": "value3", // <- remove comma
}


I came up with,



tr -d 'n' | 
sed -E 's:,(s*}):1:g' |
jq .


and it works but I want to get this fully in sed.



I came up with,



sed -E '/,s*$/ { N; s:,s*(ns*},?):1: }'


which works for above input but fails for



{
"key1": "value1",
"object": {
"key2": "value2",
},
"key3": "value3",
"key4": "value4", // <- remove comma
}


as N reads the next line and starts over from the line after next.



// output sed -E '/,s*$/ { N;l }' using l/look command
{
"key1": "value1",n "object": {$
"key1": "value1",
"object": {
"key2": "value2",n },$
"key2": "value2",
},
"key3": "value3",n "key4": "value4",$
"key3": "value3",
"key4": "value4",
}


Update:



Adding another example for testing:



{
"key1": "value1",
"object1": {
"object2": {
"key2": "value2"
},
},
"key3": "value3",
}


Update:



This is working for whatever I've thrown at it.



sed -E -n 'H; x; s:,(s*ns*}):1:; P; ${x; p}' | 
sed '1 d'


Explanation:



sed -E -n 'H; x; P; ${x; p}'


-n 'H; x' to get every line appended to the next line in pattern space (except for the last line which is simply printed with ${x; p})



and



s:,(s*ns*}):1:;


to remove the trailing comma in the pattern space.










share|improve this question




















  • 4





    Can you just fix the thing that is generating the invalid JSON instead? Because this isn't really the sort of problem you're going to solve robustly using sed.

    – larsks
    Nov 8 '18 at 3:15











  • There are JSON libraries for practically all languages. If you're getting invalid JSON like this, it's a sure sign that the creator rolled their own code instead of using a proper library, and they didn't know what they were doing. Tell them to fix it.

    – Barmar
    Nov 8 '18 at 3:20






  • 1





    Because if they can't even get commas right, they've probably got other problems as well, such as escaping special characters in strings. You'll drive yourself crazy trying to work around all their bugs.

    – Barmar
    Nov 8 '18 at 3:21






  • 2





    Anything you do will probably fail for something like key: "foo,}", it will remove the comma that's inside the string.

    – Barmar
    Nov 8 '18 at 3:22











  • "I want to remove trailing comma from json" -- your input is not JSON (as JSONs do not have trailing commas). Assuming your input is JSON, sed is not the tool for handling it. Use jq or a programming language.

    – axiac
    Nov 8 '18 at 5:59
















2















I want to remove trailing comma from json as,



{
"key1": "value1",
"object": {
"key2": "value2", // <- remove comma
},
"key3": "value3", // <- remove comma
}


I came up with,



tr -d 'n' | 
sed -E 's:,(s*}):1:g' |
jq .


and it works but I want to get this fully in sed.



I came up with,



sed -E '/,s*$/ { N; s:,s*(ns*},?):1: }'


which works for above input but fails for



{
"key1": "value1",
"object": {
"key2": "value2",
},
"key3": "value3",
"key4": "value4", // <- remove comma
}


as N reads the next line and starts over from the line after next.



// output sed -E '/,s*$/ { N;l }' using l/look command
{
"key1": "value1",n "object": {$
"key1": "value1",
"object": {
"key2": "value2",n },$
"key2": "value2",
},
"key3": "value3",n "key4": "value4",$
"key3": "value3",
"key4": "value4",
}


Update:



Adding another example for testing:



{
"key1": "value1",
"object1": {
"object2": {
"key2": "value2"
},
},
"key3": "value3",
}


Update:



This is working for whatever I've thrown at it.



sed -E -n 'H; x; s:,(s*ns*}):1:; P; ${x; p}' | 
sed '1 d'


Explanation:



sed -E -n 'H; x; P; ${x; p}'


-n 'H; x' to get every line appended to the next line in pattern space (except for the last line which is simply printed with ${x; p})



and



s:,(s*ns*}):1:;


to remove the trailing comma in the pattern space.










share|improve this question




















  • 4





    Can you just fix the thing that is generating the invalid JSON instead? Because this isn't really the sort of problem you're going to solve robustly using sed.

    – larsks
    Nov 8 '18 at 3:15











  • There are JSON libraries for practically all languages. If you're getting invalid JSON like this, it's a sure sign that the creator rolled their own code instead of using a proper library, and they didn't know what they were doing. Tell them to fix it.

    – Barmar
    Nov 8 '18 at 3:20






  • 1





    Because if they can't even get commas right, they've probably got other problems as well, such as escaping special characters in strings. You'll drive yourself crazy trying to work around all their bugs.

    – Barmar
    Nov 8 '18 at 3:21






  • 2





    Anything you do will probably fail for something like key: "foo,}", it will remove the comma that's inside the string.

    – Barmar
    Nov 8 '18 at 3:22











  • "I want to remove trailing comma from json" -- your input is not JSON (as JSONs do not have trailing commas). Assuming your input is JSON, sed is not the tool for handling it. Use jq or a programming language.

    – axiac
    Nov 8 '18 at 5:59














2












2








2


3






I want to remove trailing comma from json as,



{
"key1": "value1",
"object": {
"key2": "value2", // <- remove comma
},
"key3": "value3", // <- remove comma
}


I came up with,



tr -d 'n' | 
sed -E 's:,(s*}):1:g' |
jq .


and it works but I want to get this fully in sed.



I came up with,



sed -E '/,s*$/ { N; s:,s*(ns*},?):1: }'


which works for above input but fails for



{
"key1": "value1",
"object": {
"key2": "value2",
},
"key3": "value3",
"key4": "value4", // <- remove comma
}


as N reads the next line and starts over from the line after next.



// output sed -E '/,s*$/ { N;l }' using l/look command
{
"key1": "value1",n "object": {$
"key1": "value1",
"object": {
"key2": "value2",n },$
"key2": "value2",
},
"key3": "value3",n "key4": "value4",$
"key3": "value3",
"key4": "value4",
}


Update:



Adding another example for testing:



{
"key1": "value1",
"object1": {
"object2": {
"key2": "value2"
},
},
"key3": "value3",
}


Update:



This is working for whatever I've thrown at it.



sed -E -n 'H; x; s:,(s*ns*}):1:; P; ${x; p}' | 
sed '1 d'


Explanation:



sed -E -n 'H; x; P; ${x; p}'


-n 'H; x' to get every line appended to the next line in pattern space (except for the last line which is simply printed with ${x; p})



and



s:,(s*ns*}):1:;


to remove the trailing comma in the pattern space.










share|improve this question
















I want to remove trailing comma from json as,



{
"key1": "value1",
"object": {
"key2": "value2", // <- remove comma
},
"key3": "value3", // <- remove comma
}


I came up with,



tr -d 'n' | 
sed -E 's:,(s*}):1:g' |
jq .


and it works but I want to get this fully in sed.



I came up with,



sed -E '/,s*$/ { N; s:,s*(ns*},?):1: }'


which works for above input but fails for



{
"key1": "value1",
"object": {
"key2": "value2",
},
"key3": "value3",
"key4": "value4", // <- remove comma
}


as N reads the next line and starts over from the line after next.



// output sed -E '/,s*$/ { N;l }' using l/look command
{
"key1": "value1",n "object": {$
"key1": "value1",
"object": {
"key2": "value2",n },$
"key2": "value2",
},
"key3": "value3",n "key4": "value4",$
"key3": "value3",
"key4": "value4",
}


Update:



Adding another example for testing:



{
"key1": "value1",
"object1": {
"object2": {
"key2": "value2"
},
},
"key3": "value3",
}


Update:



This is working for whatever I've thrown at it.



sed -E -n 'H; x; s:,(s*ns*}):1:; P; ${x; p}' | 
sed '1 d'


Explanation:



sed -E -n 'H; x; P; ${x; p}'


-n 'H; x' to get every line appended to the next line in pattern space (except for the last line which is simply printed with ${x; p})



and



s:,(s*ns*}):1:;


to remove the trailing comma in the pattern space.







json bash sed






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 22:58







hIpPy

















asked Nov 8 '18 at 3:13









hIpPyhIpPy

1,84353049




1,84353049








  • 4





    Can you just fix the thing that is generating the invalid JSON instead? Because this isn't really the sort of problem you're going to solve robustly using sed.

    – larsks
    Nov 8 '18 at 3:15











  • There are JSON libraries for practically all languages. If you're getting invalid JSON like this, it's a sure sign that the creator rolled their own code instead of using a proper library, and they didn't know what they were doing. Tell them to fix it.

    – Barmar
    Nov 8 '18 at 3:20






  • 1





    Because if they can't even get commas right, they've probably got other problems as well, such as escaping special characters in strings. You'll drive yourself crazy trying to work around all their bugs.

    – Barmar
    Nov 8 '18 at 3:21






  • 2





    Anything you do will probably fail for something like key: "foo,}", it will remove the comma that's inside the string.

    – Barmar
    Nov 8 '18 at 3:22











  • "I want to remove trailing comma from json" -- your input is not JSON (as JSONs do not have trailing commas). Assuming your input is JSON, sed is not the tool for handling it. Use jq or a programming language.

    – axiac
    Nov 8 '18 at 5:59














  • 4





    Can you just fix the thing that is generating the invalid JSON instead? Because this isn't really the sort of problem you're going to solve robustly using sed.

    – larsks
    Nov 8 '18 at 3:15











  • There are JSON libraries for practically all languages. If you're getting invalid JSON like this, it's a sure sign that the creator rolled their own code instead of using a proper library, and they didn't know what they were doing. Tell them to fix it.

    – Barmar
    Nov 8 '18 at 3:20






  • 1





    Because if they can't even get commas right, they've probably got other problems as well, such as escaping special characters in strings. You'll drive yourself crazy trying to work around all their bugs.

    – Barmar
    Nov 8 '18 at 3:21






  • 2





    Anything you do will probably fail for something like key: "foo,}", it will remove the comma that's inside the string.

    – Barmar
    Nov 8 '18 at 3:22











  • "I want to remove trailing comma from json" -- your input is not JSON (as JSONs do not have trailing commas). Assuming your input is JSON, sed is not the tool for handling it. Use jq or a programming language.

    – axiac
    Nov 8 '18 at 5:59








4




4





Can you just fix the thing that is generating the invalid JSON instead? Because this isn't really the sort of problem you're going to solve robustly using sed.

– larsks
Nov 8 '18 at 3:15





Can you just fix the thing that is generating the invalid JSON instead? Because this isn't really the sort of problem you're going to solve robustly using sed.

– larsks
Nov 8 '18 at 3:15













There are JSON libraries for practically all languages. If you're getting invalid JSON like this, it's a sure sign that the creator rolled their own code instead of using a proper library, and they didn't know what they were doing. Tell them to fix it.

– Barmar
Nov 8 '18 at 3:20





There are JSON libraries for practically all languages. If you're getting invalid JSON like this, it's a sure sign that the creator rolled their own code instead of using a proper library, and they didn't know what they were doing. Tell them to fix it.

– Barmar
Nov 8 '18 at 3:20




1




1





Because if they can't even get commas right, they've probably got other problems as well, such as escaping special characters in strings. You'll drive yourself crazy trying to work around all their bugs.

– Barmar
Nov 8 '18 at 3:21





Because if they can't even get commas right, they've probably got other problems as well, such as escaping special characters in strings. You'll drive yourself crazy trying to work around all their bugs.

– Barmar
Nov 8 '18 at 3:21




2




2





Anything you do will probably fail for something like key: "foo,}", it will remove the comma that's inside the string.

– Barmar
Nov 8 '18 at 3:22





Anything you do will probably fail for something like key: "foo,}", it will remove the comma that's inside the string.

– Barmar
Nov 8 '18 at 3:22













"I want to remove trailing comma from json" -- your input is not JSON (as JSONs do not have trailing commas). Assuming your input is JSON, sed is not the tool for handling it. Use jq or a programming language.

– axiac
Nov 8 '18 at 5:59





"I want to remove trailing comma from json" -- your input is not JSON (as JSONs do not have trailing commas). Assuming your input is JSON, sed is not the tool for handling it. Use jq or a programming language.

– axiac
Nov 8 '18 at 5:59












4 Answers
4






active

oldest

votes


















2














Since the input seems to be some kind of extension of JSON, you could use a command-line tool intended for such extensions. For example:



$ hjson -j < input.txt


or:



$ any-json --input-format=hjson input.txt


Output in both cases



{
"key1": "value1",
"object": {
"key2": "value2"
},
"key3": "value3"
}





share|improve this answer
























  • Good answer! On the other hand, json should just support the trailing comma! :)

    – hek2mgl
    Nov 13 '18 at 10:54





















2














Using the hold buffer:



sed '/^ *}/{H;x;s/([^}]),n/1n/;b};x;/^ *}/d' input


This is just a sed exercise, I don't think sed is the right tool for this job. It also needs a newline at the end or that the file ends with a }.






share|improve this answer


























  • I added another sample json for testing where this sed fails.

    – hIpPy
    Nov 13 '18 at 9:54











  • updated the answer accordingly.

    – perreal
    Nov 13 '18 at 10:29











  • This is not working for the new sample json I added. Are you sure this work? I'm on and sed (GNU sed) 4.5 with GNU bash, version 4.4.19(2)-release (x86_64-pc-msys), so I'm interested in the difference. Btw, I updated with an answer.

    – hIpPy
    Nov 15 '18 at 23:01













  • Can you comment on this: tio.run/##K05N0U3PK/3/Xz9OQSumVr/aw7rCulg/RiM6rjY2RlMnJk8/…

    – perreal
    Nov 16 '18 at 3:56











  • Overall the accepted answer is better answer for the question that is titled now as hjson handles comments (both line, block), trailing comma, but thanks for pointing me in the right direction with sed.

    – hIpPy
    Nov 18 '18 at 18:06



















1














Not an answer with sed but a (python) solution:



# load as python dictionary
d = {
"key1": "value1",
"object": {
"key2": "value2",
},
"key3": "value3",
}

import json

json.dumps(d) # valid json string





share|improve this answer































    0














    Here is one in GNU awk. It uses " as field separator and removes commas before [ n]*} from odd fields (outside quotes, will probably fail for "escaped " inside"). Added "key4": "value4,}", to the file:



    $ cat file
    {
    "key1": "value1",
    "object": {
    "key2": "value2",
    },
    "key3": "value3",
    "key4": "value4,}",
    }


    The script processes the whole file as a single record (RS="^$") so it might not work for big files as-is:



    $ awk '
    BEGIN {
    FS=OFS="""
    RS="^$"
    }
    {
    for(i=1;i<=NF;i++) { # or i+=2 and remove the if
    if(i%2)
    $i=gensub(/,([ n]*})/,"\1","g",$i)
    }
    }1' file


    Output:



    {
    "key1": "value1",
    "object": {
    "key2": "value2"
    },
    "key3": "value3",
    "key4": "value4,}"
    }





    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%2f53201028%2fremove-trailing-json-comma-with-command-line-tools%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      Since the input seems to be some kind of extension of JSON, you could use a command-line tool intended for such extensions. For example:



      $ hjson -j < input.txt


      or:



      $ any-json --input-format=hjson input.txt


      Output in both cases



      {
      "key1": "value1",
      "object": {
      "key2": "value2"
      },
      "key3": "value3"
      }





      share|improve this answer
























      • Good answer! On the other hand, json should just support the trailing comma! :)

        – hek2mgl
        Nov 13 '18 at 10:54


















      2














      Since the input seems to be some kind of extension of JSON, you could use a command-line tool intended for such extensions. For example:



      $ hjson -j < input.txt


      or:



      $ any-json --input-format=hjson input.txt


      Output in both cases



      {
      "key1": "value1",
      "object": {
      "key2": "value2"
      },
      "key3": "value3"
      }





      share|improve this answer
























      • Good answer! On the other hand, json should just support the trailing comma! :)

        – hek2mgl
        Nov 13 '18 at 10:54
















      2












      2








      2







      Since the input seems to be some kind of extension of JSON, you could use a command-line tool intended for such extensions. For example:



      $ hjson -j < input.txt


      or:



      $ any-json --input-format=hjson input.txt


      Output in both cases



      {
      "key1": "value1",
      "object": {
      "key2": "value2"
      },
      "key3": "value3"
      }





      share|improve this answer













      Since the input seems to be some kind of extension of JSON, you could use a command-line tool intended for such extensions. For example:



      $ hjson -j < input.txt


      or:



      $ any-json --input-format=hjson input.txt


      Output in both cases



      {
      "key1": "value1",
      "object": {
      "key2": "value2"
      },
      "key3": "value3"
      }






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 10 '18 at 16:48









      peakpeak

      31.3k83957




      31.3k83957













      • Good answer! On the other hand, json should just support the trailing comma! :)

        – hek2mgl
        Nov 13 '18 at 10:54





















      • Good answer! On the other hand, json should just support the trailing comma! :)

        – hek2mgl
        Nov 13 '18 at 10:54



















      Good answer! On the other hand, json should just support the trailing comma! :)

      – hek2mgl
      Nov 13 '18 at 10:54







      Good answer! On the other hand, json should just support the trailing comma! :)

      – hek2mgl
      Nov 13 '18 at 10:54















      2














      Using the hold buffer:



      sed '/^ *}/{H;x;s/([^}]),n/1n/;b};x;/^ *}/d' input


      This is just a sed exercise, I don't think sed is the right tool for this job. It also needs a newline at the end or that the file ends with a }.






      share|improve this answer


























      • I added another sample json for testing where this sed fails.

        – hIpPy
        Nov 13 '18 at 9:54











      • updated the answer accordingly.

        – perreal
        Nov 13 '18 at 10:29











      • This is not working for the new sample json I added. Are you sure this work? I'm on and sed (GNU sed) 4.5 with GNU bash, version 4.4.19(2)-release (x86_64-pc-msys), so I'm interested in the difference. Btw, I updated with an answer.

        – hIpPy
        Nov 15 '18 at 23:01













      • Can you comment on this: tio.run/##K05N0U3PK/3/Xz9OQSumVr/aw7rCulg/RiM6rjY2RlMnJk8/…

        – perreal
        Nov 16 '18 at 3:56











      • Overall the accepted answer is better answer for the question that is titled now as hjson handles comments (both line, block), trailing comma, but thanks for pointing me in the right direction with sed.

        – hIpPy
        Nov 18 '18 at 18:06
















      2














      Using the hold buffer:



      sed '/^ *}/{H;x;s/([^}]),n/1n/;b};x;/^ *}/d' input


      This is just a sed exercise, I don't think sed is the right tool for this job. It also needs a newline at the end or that the file ends with a }.






      share|improve this answer


























      • I added another sample json for testing where this sed fails.

        – hIpPy
        Nov 13 '18 at 9:54











      • updated the answer accordingly.

        – perreal
        Nov 13 '18 at 10:29











      • This is not working for the new sample json I added. Are you sure this work? I'm on and sed (GNU sed) 4.5 with GNU bash, version 4.4.19(2)-release (x86_64-pc-msys), so I'm interested in the difference. Btw, I updated with an answer.

        – hIpPy
        Nov 15 '18 at 23:01













      • Can you comment on this: tio.run/##K05N0U3PK/3/Xz9OQSumVr/aw7rCulg/RiM6rjY2RlMnJk8/…

        – perreal
        Nov 16 '18 at 3:56











      • Overall the accepted answer is better answer for the question that is titled now as hjson handles comments (both line, block), trailing comma, but thanks for pointing me in the right direction with sed.

        – hIpPy
        Nov 18 '18 at 18:06














      2












      2








      2







      Using the hold buffer:



      sed '/^ *}/{H;x;s/([^}]),n/1n/;b};x;/^ *}/d' input


      This is just a sed exercise, I don't think sed is the right tool for this job. It also needs a newline at the end or that the file ends with a }.






      share|improve this answer















      Using the hold buffer:



      sed '/^ *}/{H;x;s/([^}]),n/1n/;b};x;/^ *}/d' input


      This is just a sed exercise, I don't think sed is the right tool for this job. It also needs a newline at the end or that the file ends with a }.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 13 '18 at 10:28

























      answered Nov 8 '18 at 4:06









      perrealperreal

      71.9k9110138




      71.9k9110138













      • I added another sample json for testing where this sed fails.

        – hIpPy
        Nov 13 '18 at 9:54











      • updated the answer accordingly.

        – perreal
        Nov 13 '18 at 10:29











      • This is not working for the new sample json I added. Are you sure this work? I'm on and sed (GNU sed) 4.5 with GNU bash, version 4.4.19(2)-release (x86_64-pc-msys), so I'm interested in the difference. Btw, I updated with an answer.

        – hIpPy
        Nov 15 '18 at 23:01













      • Can you comment on this: tio.run/##K05N0U3PK/3/Xz9OQSumVr/aw7rCulg/RiM6rjY2RlMnJk8/…

        – perreal
        Nov 16 '18 at 3:56











      • Overall the accepted answer is better answer for the question that is titled now as hjson handles comments (both line, block), trailing comma, but thanks for pointing me in the right direction with sed.

        – hIpPy
        Nov 18 '18 at 18:06



















      • I added another sample json for testing where this sed fails.

        – hIpPy
        Nov 13 '18 at 9:54











      • updated the answer accordingly.

        – perreal
        Nov 13 '18 at 10:29











      • This is not working for the new sample json I added. Are you sure this work? I'm on and sed (GNU sed) 4.5 with GNU bash, version 4.4.19(2)-release (x86_64-pc-msys), so I'm interested in the difference. Btw, I updated with an answer.

        – hIpPy
        Nov 15 '18 at 23:01













      • Can you comment on this: tio.run/##K05N0U3PK/3/Xz9OQSumVr/aw7rCulg/RiM6rjY2RlMnJk8/…

        – perreal
        Nov 16 '18 at 3:56











      • Overall the accepted answer is better answer for the question that is titled now as hjson handles comments (both line, block), trailing comma, but thanks for pointing me in the right direction with sed.

        – hIpPy
        Nov 18 '18 at 18:06

















      I added another sample json for testing where this sed fails.

      – hIpPy
      Nov 13 '18 at 9:54





      I added another sample json for testing where this sed fails.

      – hIpPy
      Nov 13 '18 at 9:54













      updated the answer accordingly.

      – perreal
      Nov 13 '18 at 10:29





      updated the answer accordingly.

      – perreal
      Nov 13 '18 at 10:29













      This is not working for the new sample json I added. Are you sure this work? I'm on and sed (GNU sed) 4.5 with GNU bash, version 4.4.19(2)-release (x86_64-pc-msys), so I'm interested in the difference. Btw, I updated with an answer.

      – hIpPy
      Nov 15 '18 at 23:01







      This is not working for the new sample json I added. Are you sure this work? I'm on and sed (GNU sed) 4.5 with GNU bash, version 4.4.19(2)-release (x86_64-pc-msys), so I'm interested in the difference. Btw, I updated with an answer.

      – hIpPy
      Nov 15 '18 at 23:01















      Can you comment on this: tio.run/##K05N0U3PK/3/Xz9OQSumVr/aw7rCulg/RiM6rjY2RlMnJk8/…

      – perreal
      Nov 16 '18 at 3:56





      Can you comment on this: tio.run/##K05N0U3PK/3/Xz9OQSumVr/aw7rCulg/RiM6rjY2RlMnJk8/…

      – perreal
      Nov 16 '18 at 3:56













      Overall the accepted answer is better answer for the question that is titled now as hjson handles comments (both line, block), trailing comma, but thanks for pointing me in the right direction with sed.

      – hIpPy
      Nov 18 '18 at 18:06





      Overall the accepted answer is better answer for the question that is titled now as hjson handles comments (both line, block), trailing comma, but thanks for pointing me in the right direction with sed.

      – hIpPy
      Nov 18 '18 at 18:06











      1














      Not an answer with sed but a (python) solution:



      # load as python dictionary
      d = {
      "key1": "value1",
      "object": {
      "key2": "value2",
      },
      "key3": "value3",
      }

      import json

      json.dumps(d) # valid json string





      share|improve this answer




























        1














        Not an answer with sed but a (python) solution:



        # load as python dictionary
        d = {
        "key1": "value1",
        "object": {
        "key2": "value2",
        },
        "key3": "value3",
        }

        import json

        json.dumps(d) # valid json string





        share|improve this answer


























          1












          1








          1







          Not an answer with sed but a (python) solution:



          # load as python dictionary
          d = {
          "key1": "value1",
          "object": {
          "key2": "value2",
          },
          "key3": "value3",
          }

          import json

          json.dumps(d) # valid json string





          share|improve this answer













          Not an answer with sed but a (python) solution:



          # load as python dictionary
          d = {
          "key1": "value1",
          "object": {
          "key2": "value2",
          },
          "key3": "value3",
          }

          import json

          json.dumps(d) # valid json string






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 8 '18 at 5:26









          Reut SharabaniReut Sharabani

          22.9k44665




          22.9k44665























              0














              Here is one in GNU awk. It uses " as field separator and removes commas before [ n]*} from odd fields (outside quotes, will probably fail for "escaped " inside"). Added "key4": "value4,}", to the file:



              $ cat file
              {
              "key1": "value1",
              "object": {
              "key2": "value2",
              },
              "key3": "value3",
              "key4": "value4,}",
              }


              The script processes the whole file as a single record (RS="^$") so it might not work for big files as-is:



              $ awk '
              BEGIN {
              FS=OFS="""
              RS="^$"
              }
              {
              for(i=1;i<=NF;i++) { # or i+=2 and remove the if
              if(i%2)
              $i=gensub(/,([ n]*})/,"\1","g",$i)
              }
              }1' file


              Output:



              {
              "key1": "value1",
              "object": {
              "key2": "value2"
              },
              "key3": "value3",
              "key4": "value4,}"
              }





              share|improve this answer






























                0














                Here is one in GNU awk. It uses " as field separator and removes commas before [ n]*} from odd fields (outside quotes, will probably fail for "escaped " inside"). Added "key4": "value4,}", to the file:



                $ cat file
                {
                "key1": "value1",
                "object": {
                "key2": "value2",
                },
                "key3": "value3",
                "key4": "value4,}",
                }


                The script processes the whole file as a single record (RS="^$") so it might not work for big files as-is:



                $ awk '
                BEGIN {
                FS=OFS="""
                RS="^$"
                }
                {
                for(i=1;i<=NF;i++) { # or i+=2 and remove the if
                if(i%2)
                $i=gensub(/,([ n]*})/,"\1","g",$i)
                }
                }1' file


                Output:



                {
                "key1": "value1",
                "object": {
                "key2": "value2"
                },
                "key3": "value3",
                "key4": "value4,}"
                }





                share|improve this answer




























                  0












                  0








                  0







                  Here is one in GNU awk. It uses " as field separator and removes commas before [ n]*} from odd fields (outside quotes, will probably fail for "escaped " inside"). Added "key4": "value4,}", to the file:



                  $ cat file
                  {
                  "key1": "value1",
                  "object": {
                  "key2": "value2",
                  },
                  "key3": "value3",
                  "key4": "value4,}",
                  }


                  The script processes the whole file as a single record (RS="^$") so it might not work for big files as-is:



                  $ awk '
                  BEGIN {
                  FS=OFS="""
                  RS="^$"
                  }
                  {
                  for(i=1;i<=NF;i++) { # or i+=2 and remove the if
                  if(i%2)
                  $i=gensub(/,([ n]*})/,"\1","g",$i)
                  }
                  }1' file


                  Output:



                  {
                  "key1": "value1",
                  "object": {
                  "key2": "value2"
                  },
                  "key3": "value3",
                  "key4": "value4,}"
                  }





                  share|improve this answer















                  Here is one in GNU awk. It uses " as field separator and removes commas before [ n]*} from odd fields (outside quotes, will probably fail for "escaped " inside"). Added "key4": "value4,}", to the file:



                  $ cat file
                  {
                  "key1": "value1",
                  "object": {
                  "key2": "value2",
                  },
                  "key3": "value3",
                  "key4": "value4,}",
                  }


                  The script processes the whole file as a single record (RS="^$") so it might not work for big files as-is:



                  $ awk '
                  BEGIN {
                  FS=OFS="""
                  RS="^$"
                  }
                  {
                  for(i=1;i<=NF;i++) { # or i+=2 and remove the if
                  if(i%2)
                  $i=gensub(/,([ n]*})/,"\1","g",$i)
                  }
                  }1' file


                  Output:



                  {
                  "key1": "value1",
                  "object": {
                  "key2": "value2"
                  },
                  "key3": "value3",
                  "key4": "value4,}"
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 8 '18 at 5:21

























                  answered Nov 8 '18 at 4:46









                  James BrownJames Brown

                  18.3k31635




                  18.3k31635






























                      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%2f53201028%2fremove-trailing-json-comma-with-command-line-tools%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







                      Popular posts from this blog

                      Florida Star v. B. J. F.

                      Error while running script in elastic search , gateway timeout

                      Adding quotations to stringified JSON object values