Lire un fichier Json
Source: Parsing values from a JSON file in Python
fichier de depart
{
"math":[{"cours01":"derivees","cours01":"integrale"},{"exo01":"blabla","exo2":"blabla"}],
"physique":{"cours01":"electrostatic"},
"anglais":"cool",
"chimie":{"cours01":"organique"}
}
code
from pprint import pprint
import json
json_data=open('JsonFileExample')
print type(json_data), json_data
data = json.load(json_data)
print type(data)
pprint(data)
json_data.close()
resultat
<type 'file'> <open file 'JsonFileExample', mode 'r' at 0x100456300>
<type 'dict'>
{u'anglais': u'cool',
u'chimie': {u'cours01': u'organique'},
u'math': [{u'cours01': u'integrale'},
{u'exo01': u'blabla', u'exo2': u'blabla'}],
u'physique': {u'cours01': u'electrostatic'}}
Exemple(s) d'application
Parser le fichier Bookmarks de Chrome
Fichier exemple: [attachment:390]
import json
from pprint import pprint
import datetime
def getFiletime(dt):
microseconds = int(dt, 16) / 10
seconds, microseconds = divmod(microseconds, 1000000)
days, seconds = divmod(seconds, 86400)
return datetime.datetime(1601, 1, 1) + datetime.timedelta(days, seconds, microseconds)
json_data=open('Bookmarks.txt')
data = json.load(json_data)
dict_url = {}
for key, value in data.iteritems():
fiter = 0
dicof = []
if type(value) is dict:
fiter = 1
dicof.append(value)
while fiter == 1:
fiter = 0
dicof_tmp = []
for i in dicof:
if type(i) is dict:
found_url = ''
for key, value in i.iteritems():
if type(value) is dict:
fiter = 1
dicof_tmp.append(value)
if type(value) is list:
fiter = 1
dicof_tmp.append(value)
if key == 'url':
dict_url[value] = []
found_url = value
if dict_url.has_key(found_url) and key == 'date_added':
dict_url[found_url]\
.append(format(getFiletime(hex(int(value)*10)[2:17]),\
'%a, %d %B %Y %H:%M:%S %Z'))
if type(i) is list:
for value in i:
if type(value) is dict:
fiter = 1
dicof_tmp.append(value)
if type(value) is list:
fiter = 1
dicof_tmp.append(value)
dicof = []
dicof = dicof_tmp
for key, value in dict_url.iteritems():
print key, value
json_data.close()
Resultat:
http://www.djangofoo.com/17/django-mod_wsgi-deploy-exampl ['Tue, 26 March 2013 00:52:20 ']
http://www.youtube.com/watch?v=dQiNVk_u0po ['Mon, 10 December 2012 04:13:51 ']
http://www.youtube.com/watch?v=1y6smkh6c-0 ['Mon, 10 December 2012 04:14:12 ']
http://www.youtube.com/watch?v=_Yo4MVQp6yg ['Tue, 22 April 2014 00:49:21 ']
https://code.djangoproject.com/wiki/django_apache_and_mod_wsgi ['Tue, 18 December 2012 19:10:12 ']
http://www.google.com/ ['Tue, 22 January 2013 23:07:17 ']
http://www.youtube.com/watch?v=PDboaDrHGbA ['Mon, 10 December 2012 06:09:46 ']
Recherches associées
Liens | Site |
---|---|
How to parse the date_added field in Chrome Bookmarks file? | stackoverflow |