如何从python中的JSON文件中删除注释行

use*_*636 5 python json

我正在获取具有以下格式的JSON文件:

// 20170407
// http://info.employeeportal.org

{
 "EmployeeDataList": [
{
 "EmployeeCode": "200005ABH9",
 "Skill": CT70,
 "Sales": 0.0,
 "LostSales": 1010.4
} 
 ]
} 
Run Code Online (Sandbox Code Playgroud)

需要删除文件中存在的多余注释行。

我尝试使用以下代码:

import json
import commentjson

with open('EmployeeDataList.json') as json_data:
            employee_data = json.load(json_data)
            '''employee_data = json.dump(json.load(json_data))'''
            '''employee_data = commentjson.load(json_data)'''
            print(employee_data)`
Run Code Online (Sandbox Code Playgroud)

仍然无法从文件中删除注释,并以正确的格式导入JSON文件。

无法到达哪里出了问题?在这方面的任何方向都受到高度赞赏。

Ble*_*der 6

你没有commentjson正确使用。它具有与json模块相同的接口:

import commentjson

with open('EmployeeDataList.json', 'r') as handle:
    employee_data = commentjson.load(handle)

print(employee_data)
Run Code Online (Sandbox Code Playgroud)

尽管在这种情况下,您的注释足够简单,您可能不需要安装额外的模块来删除它们:

import json

with open('EmployeeDataList.json', 'r') as handle:
    fixed_json = ''.join(line for line in handle if not line.startswith('//'))
    employee_data = json.loads(fixed_json)

print(employee_data)
Run Code Online (Sandbox Code Playgroud)

请注意,这里两个代码片段之间的区别json.loads在于使用了而不是json.load,因为您正在解析字符串而不是文件对象。

  • @Posh_Pumpkin:“JSON”包含变量(`“Skill”:CT70`),而不仅仅是注释。 (2认同)

kpi*_*pie -1

如果每次的行数相同,你可以这样做:

fh = open('EmployeeDataList.NOTjson',"r")
rawText = fh.read()
json_data = rawText[rawText.index("\n",3)+1:]
Run Code Online (Sandbox Code Playgroud)

这样 json_data 现在就是没有前 3 行的文本字符串。