How to parse json file with c
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?
I can not imagine a json file "auto created by other program" would contain comments inside. Because json spec defines no comment at all, and that is by design, so no json library would output a json file with comment.
Those comments are usually added later, by a human. No exception in this case. The OP mentioned that in his post: //"birthday": "nothing" //I comment this line
.
So the real question should be, how do I properly comment some content in a json file, yet maintaining its compliance with spec and hence its compatibility with other json libraries?
And the answer is, rename your field to another name. Example:
{
"foo": "content for foo",
"bar": "content for bar"
}
can be changed into:
{
"foo": "content for foo",
"this_is_bar_but_been_commented_out": "content for bar"
}
This will work just fine most of the time because the consumer will very likely ignore unexpected fields (but not always, it depends on your json file consumer's implementation. So YMMV.)
一种方法是将非常接近的JSON文本转换为实际的JSON文本,然后将其传递给解析器,如下所示:
input_str = re.sub(r'n', '', input_str)
input_str = re.sub(r'//.*n', 'n', input_str)
data = json.loads(input_str)
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)
链接地址: http://www.djcxy.com/p/3398.html
上一篇: 你如何给json IAM策略添加评论?
下一篇: 如何用c解析json文件