'How to read JSON file with comments?
The comment are causing errors. I have a contents.json file which looks like:
{
"Fridge": [
["apples"],
["chips","cake","10"] // This comment here is causing error
],
"car": [
["engine","tires","fuel"],
]
}
My python script is like this
import json
jsonfile = open('contents.json','r')
jsondata = jsonfile.read()
objec = json.loads(jsondata)
list_o = objec['Fridge']
for i in (list_o):
print(i)
In my list_o, i am trying to load Fridge from contents.jsonfile, when JSON file has that comment, it gives me an error, when the JSON file doesn't have the comment, the script runs properly.
I understand that comments is not proper JSON format, but is there any way to ignore comments of JSON file?
Solution 1:[1]
Read the file per line and remove the comment part.
import json
jsondata = ""
with open('contents.json', 'r') as jsonfile:
for line in jsonfile:
jsondata += line.split("//")[0]
objec = json.loads(jsondata)
list_o = objec['Fridge']
for i in (list_o):
print(i)
['apples']
['chips', 'cake', '10']
Update
You can also easily just use a library such as commentjson. Just replace :
objec = json.loads(jsondata)
To
import commentjson # python3 -m pip install commentjson
objec = commentjson.loads(jsondata)
Solution 2:[2]
@NielGodfreyPonciano's answer would work most of the time but would fail when // is part of a string.
For a more robust solution you can parse it as JSON5, a superset of JSON that supports comments, with the pyjson5 module:
import json5
data = '''{
"Fridge": [
["apples"],
["chips","cake","10"] // This comment here is causing error
],
"car": [
["engine","tires","fuel"],
]
}'''
print(json5.loads(data))
This outputs:
{'Fridge': [['apples'], ['chips', 'cake', '10']], 'car': [['engine', 'tires', 'fuel']]}
Solution 3:[3]
"Errors due to comments" is precisely what should happen because JSON documents should NOT contain comments. You will have to fix the data at the source before consuming. In other words, if your data contains javascript-style comments, then it is not a JSON anymore (just a random non-standard text file)
At the consuming side, any attempts to remove comments could be unsafe as JSON documents do not need to have newlines/pretty printed.
Solution 4:[4]
Following @blhsing's and @NielGodfreyPonciano's answers, you could also achieve that with only built-in modules by using regular expressions:
import re
import json
with open("contents.json", "r") as JSONfile:
objec = json.loads("".join(re.split(r"(?://|#).*(?=\n)", JSONfile.read())).strip())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | blhsing |
| Solution 3 | |
| Solution 4 |
