I have a json file, such as the following:
{ "author":"John", "desc": "If it is important to decode all valid JSON correctly \ and speed isn't as important, you can use the built-in json module, \ orsimplejson. They are basically the same but sometimes simplej \ further along than the version of it that is included with \ distribution." //"birthday": "nothing" //I comment this line }
This file is auto created by another program. How do I parse it with Python?
No. JSON is data-only. If you include a comment, then it must be data too. You could have a designated data element called "_comment" (or something) that should be ignored by apps that use the JSON data.
JSON doesn't permit comments by design. As explained by its creator Douglas Crockford. I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability.
Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.
jsoncomment is good, but inline comment is not supported.
Check out jstyleson, which support
Comments are NOT preserved. jstyleson
first removes all comments and trailing commas, then uses the standard json module. It seems like function arguments are forwarded and work as expected. It also exposes dispose
to return the cleaned string contents without parsing.
pip install jstyleson
import jstyleson result_dict = jstyleson.loads(invalid_json_str) # OK jstyleson.dumps(result_dict)
I recommend everyone switch to a JSON5 library instead. JSON5 is JSON with JavaScript features/support. It's the most popular JSON language extension in the world. It has comments, support for trailing commas in objects/arrays, support for single-quoted keys/strings, support for unquoted object keys, etc. And there's proper parser libraries with deep test suites and everything working perfectly.
There are two different, high-quality Python implementations:
https://github.com/dpranke/pyjson5 (written entirely in Python, it's slow, has its own test suite, project started in 2015 and more "liked"). PyPi Page: https://pypi.org/project/json5/
Recommended: https://github.com/Kijewski/pyjson5 (uses compiled native code via Cython which is much faster, uses the official json5 js test suite instead of its own, project started in 2018). PyPi Page: https://pypi.org/project/pyjson5/
Here's the JSON5 spec: https://json5.org/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With