How to parse json file with c-style comments?

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/


jsoncomment is good, but inline comment is not supported.

Check out jstyleson, which support

  • inline comment
  • single-line comment
  • multi-line comment
  • trailing comma.

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.

Example

Install

pip install jstyleson

Usage

import jstyleson
result_dict = jstyleson.loads(invalid_json_str) # OK
jstyleson.dumps(result_dict)

I have not personally used it, but the jsoncomment python package supports parsing a JSON file with comments.

You use it in place of the JSON parser as follows:

parser = JsonComment(json)
parsed_object = parser.loads(jsonString)

Tags:

Python

Json