Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove comment lines from a JSON file in python

Tags:

python

json

I am getting a JSON file with following format :

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

{
 "EmployeeDataList": [
{
 "EmployeeCode": "200005ABH9",
 "Skill": CT70,
 "Sales": 0.0,
 "LostSales": 1010.4
} 
 ]
} 

Need to remove the extra comment lines present in the file.

I tried with the following code :

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

Still not able to remove the comments from the file and bring the JSON file in correct format.

Not getting where things are going wrong? Any direction in this regard is highly appreciated.Thanks in advance

like image 520
Eupheus Avatar asked Apr 09 '17 03:04

Eupheus


People also ask

How do I ignore comments in JSON?

To do this, you need to add an element to your JSON file, such as "_comment," which will contain your comment. The JSON API endpoint must ignore this particular JSON comment element.

How do you comment out a JSON file in Python?

Open the JSON file in your text editor and add comments the same way you would in Python (using # and not docstrings) or the same way you would in JavaScript (using // and not multi-line comments using /** */ ).

Does JSON have comments?

JSON does not support comments. It was also never intended to be used for configuration files where comments would be needed. Hjson is a configuration file format for humans.


2 Answers

You're not using commentjson correctly. It has the same interface as the json module:

import commentjson

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

print(employee_data)

Although in this case, your comments are simple enough that you probably don't need to install an extra module to remove them:

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)

Note the difference here between the two code snippets is that json.loads is used instead of json.load, since you're parsing a string instead of a file object.

like image 151
Blender Avatar answered Sep 20 '22 08:09

Blender


Try JSON-minify:

JSON-minify minifies blocks of JSON-like content into valid JSON by removing all whitespace and JS-style comments (single-line // and multiline /* .. */).

like image 29
hailinzeng Avatar answered Sep 21 '22 08:09

hailinzeng