Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

python - How to parse json file with c-style comments?

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?

question from:https://stackoverflow.com/questions/29959191/how-to-parse-json-file-with-c-style-comments

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...