简体   繁体   中英

Remove comments from json file using Python

I have a JSON file with comments shown below, I can't read the file in python as it is an invalid JSON file and I would like to have a pythonic way to remove all the lines in the file starting with /* as shown below:

/* 1 */
[{
    "_id" : ObjectId("abe"),
    "id" : "149",
    "objectType" : "act"
},
/* 2 */
{
    "_id" : ObjectId("abe415"),
    "id" : "449899009",
    "objectType" : "ity"
}]

I have tried the code below but getting the error in loads() of JSON: '''

import JSON

with open('data.json', 'r+',encoding='utf-8-sig') as handle:
    fixed_json = ''.join(line for line in handle if not line.startswith('/*'))
    final_data = json.loads(fixed_json)

print(final_data)

'JSONDecodeError: Expecting value: line 4 column 13 (char 16)'

Thanks in advance

I found this solution:

import json
import ast

def ObjectId(a):
    return f"ObjectId(\'{a}\')"

with open('test.json', 'r+',encoding='utf-8') as handle:
    fixed_json = ''.join(line for line in handle if not line.startswith('/*'))
    
    fixed_json = str(eval(fixed_json))
 
    final_data = ast.literal_eval(json.dumps(str(fixed_json)))
    final_data = ast.literal_eval(final_data)


print(final_data)

Output is:

[{'_id': "ObjectId('abe')", 'id': '149', 'objectType': 'act'}, {'_id': "ObjectId('abe415')", 'id': '449899009', 'objectType': 'ity'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM