420 B 63 Programmation Web Avance Auteur Frdric
420 -B 63 Programmation Web Avancée Auteur : Frédéric Thériault JSON (JAVASCRIPT OBJECT NOTATION) 1
À quoi ça sert !? Format d’échange entre différentes technologies. Sérialise les objets/tableaux/… en texte JSON en utilisant des symboles : [], : , {}, … C’est une très bonne technique à utiliser pour le développement AJAX PHP supporte JSON depuis 5. 2. Site Web : http: //www. json. org/ Il est fortement conseillé de travailler en UTF-8 avec JSON (pour le transport des accents). 2
Exemple de texte JSON Le texte JSON suit le format standard de Java. Script : <script type="text/javascript"> var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW"; var json. Texte = JSON. stringify(mycars); alert(json. Texte); </script> Ceci affichera : ["Saab", "Volvo", "BMW"] (c’est le texte JSON) 3
Pour l’utiliser… Java. Script : Avoir intégré la librairie JSON à sa page Web, sauf dans certains navigateurs qui le supportent déjà. ○ Var obj. Tmp = JSON. stringify(texte) Transforme en texte JSON ○ Var obj = JSON. parse(obj. Tmp) Transforme un texte JSON en entité Java. Script 4
Pour l’utiliser… (suite) PHP En considérant un tableau comme suit : $ma. Variable = array(); $ma. Variable[] = array('John', 'Smith', 'Concierge'); $ma. Variable[] = array('Roger', 'Eddie', 'Joueur de hockey'); … On appelle la fonction json_encode($ma. Variable) pour transformer le tableau en texte JSON echo json_encode($ma. Variable); La fonction json_decode($variable) permet de construire un texte JSON en entité PHP. 5
- Slides: 5