Python-删除字符串中最后一个对象的逗号以获取有效的JSON [英] Python - Remove comma of last object in a string for valid JSON

查看:603
本文介绍了Python-删除字符串中最后一个对象的逗号以获取有效的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试弄清楚它时,我遇到了一些困难,这是使用Python将字符串转换为有效JSON的最佳方式.

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.

基本上,我需要做的是从文件中读取一个字符串(已经以JSON格式给出),并将其转换为有效的JSON.在我的情况下,唯一的问题是最后一个对象之后的":

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

由于JSON无效,因此加载JSON文件失败. 您有什么建议吗,首先是如何去除最后一个逗号,其次是如何验证字符串并确保其格式正确?

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?

推荐答案

您可以将其解析为YAML(其内联语法是JSON的更宽松的超集):

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

然后要获取有效的JSON,可以将对象转储回去:

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

import json
json.dumps(data)

这篇关于Python-删除字符串中最后一个对象的逗号以获取有效的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆