Short vitae
I'm Damien Riquet , 24 years old, a PhD. Student within the 2XS research group at the University of Lille 1 (France). I hold a Master Degree (french equivalent of an MSc) in Computer Science from the University of Lille 1.
My PhD (funded by the French Research Ministry), under the supervision of Gilles Grimaud and Michaƫl Hauspie , is about including Embedded probes for Cloud Security .
This website presents my research interests, publications and some blog entries.
Jeu 04 octobre 2012
In Python .
Tags: python json
I like to use JSON files with python.
It's very simple to read and use such files.
For example:
JSON file
{
"username" : "John Smith" ,
"age" : 42 ,
"list" : [ "a" , "b" , "c" ]
}
Python script
import json
with open ( 'file.json' ) as f :
d = json . load ( f )
print d [ 'username' ]
print d [ 'age' ]
print ',' . join ( d [ 'list' ])
will print:
I usually use JSON files to configure scripts. And such files could become easily unreadable.
That's why I wanted to include some comments, but unfortunately JSON files cannot contain comments.
So I wrote a short piece of Python code that wraps the JSON parser:
import json
import re
# Regular expression for comments
comment_re = re . compile (
'(^)?[^\S \n ]*/(?:\*(.*?)\*/[^\S \n ]*|/[^ \n ]*)($)?' ,
re . DOTALL | re . MULTILINE
)
def parse_json ( filename ):
""" Parse a JSON file
First remove comments and then use the json module package
Comments look like :
// ...
or
/*
...
*/
"""
with open ( filename ) as f :
content = '' . join ( f . readlines ())
## Looking for comments
match = comment_re . search ( content )
while match :
# single line comment
content = content [: match . start ()] + content [ match . end ():]
match = comment_re . search ( content )
print content
# Return json file
return json . loads ( content )
Feel free to use this code. Beerware / WTFPL licence.
Comment(s)
Page 1 / 1
Proudly powered by Pelican , which takes great advantage of Python .
The theme is by Smashing Magazine , thanks!