Python - Remove comma of last object in a string for valid JSON

Viewed 3661

I'm facing some difficulties while trying to figure it out, what it the optimal way to convert a string to a valid JSON, using Python.

Basically, what I need to do is to read a string (which is already given in a JSON format) from a file, and convert it to a valid JSON. The only problem in my case, is the " , " after the last object:

    {
        "InputTable" : 
        [
            {
                "ServerName":"serverOne",
                "To":"userOne", 
                "CC":"", 
                "TemplateName":"LinuxTemplate" 
            },
            {
                "ServerName":"serverTwo",
                "To":"userTwo", 
                "CC":"userFive", 
                "TemplateName":"LinuxTemplateWithCC" 

            }, << get rid of this comma

        ],
        "Params": 
        [   

            {"Col_0":"Server","Col_1":"User","Col_2":"Action"}
        ]
    }

This is how I read the file:

with open('/nfs/somePath/LinuxInput.JSON') as json_file:  
        try:
            jsonFormatInputTable = json.load(json_file)
        except:
            print ("Couldn't read JSON file, cancled operation.")
            return

Loading the JSON file fails because the JSON is not valid. Do you have any suggestion, first how to get rid of that last comma, and second how to validate the string and make sure it is in the correct format?

4 Answers

You could parse it as YAML (whose in-line syntax is a more permissive superset of JSON):

import yaml
data = yaml.load(open(json_file))

then to get valid JSON back you can dump the object back out:

import json
json.dumps(data)

If your JSON is valid except for the trailing commas, you can try using more relaxed parsers like the other solution said.

If you just want to remove the trailing commas, this regex should work.

(?<=[}\]"']),(?!\s*[{["'])

Replace all occurrences with an empty string.

import re
regex = r'''(?<=[}\]"']),(?!\s*[{["'])'''
result = re.sub(regex, "", test_str, 0)

You could using jsoncomment https://pypi.python.org/pypi/jsoncomment

import json
from jsoncomment import JsonComment

with open('/nfs/somePath/LinuxInput.JSON') as json_file:    
    parser = JsonComment(json)
    data = parser.load(json_file)

There You go:

=^..^=

test_string = """{
    "InputTable" : 
    [
        {
            "ServerName":"serverOne",
            "To":"userOne", 
            "CC":"", 
            "TemplateName":"LinuxTemplate" 
        },
        {
            "ServerName":"serverTwo",
            "To":"userTwo", 
            "CC":"userFive", 
            "TemplateName":"LinuxTemplateWithCC" 

        },

    ],
    "Params": 
    [   

        {"Col_0":"Server","Col_1":"User","Col_2":"Action"}
    ]
}"""

test_string = re.sub("},\n\n", "}\n", test_string)
valid_jonson = json.loads(test_string)
Related