python去除最后的逗号_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.

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?

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值